C++,文本文件,读取文件

代码演示:

#include
using namespace std;
#include
#include

void test() {
	//1、包含头文件

	//2、创建流对象
	ifstream ifs;

	//3、打开文件并判断文件是否成功
	ifs.open("test.txt", ios::in);
	if (!ifs.is_open())
	{
		cout << "文件打开失败" << endl;
		return;
	}

	//4、读文件
	//第一种方式
	char buf[123] = { 0 };
	while (ifs >> buf)
	{
		cout << buf << endl;
	}

	//第二种方式
	//char buf[123] = { 0 };
	//while (ifs.getline(buf, sizeof(buf)))
	//{
		//cout << buf << endl;
	//}

	//第三种方式
	//string buf;
	//while (getline(ifs, buf))
	//{
		//cout << buf << endl;
	//}

	//第四种方式
	//char c;
	//while ((c = ifs.get() != EOF))
	//{
		//cout << c;
	//}

	//5、关闭文件
	ifs.close();
}

int main() {
	test();

}

运行截图:

C++,文本文件,读取文件_第1张图片

 

你可能感兴趣的:(c++,开发语言)