#文件--C++

#include
using namespace std;
#include//文件的头文件
#include//全局函数getline的头文件

//写文件
void test01()
{
	ofstream ofs;//创建流对象
	ofs.open("test.txt", ios::out);
	ofs << "姓名:张三" << endl;
	ofs << "性别:男" << endl;
	ofs << "年龄:18" << endl;//<<用于写入
	ofs.close();
	
}

//读文件
void test02()
{
	ifstream ifs;

	ifs.open("test.txt", ios::in);
	if (!ifs.is_open())
	{
		cout << "文件打开失败" << endl;
		return;
	}

	第一种读取
	//char buf[1024] = { 0 };
	//while (ifs >> buf)//右移运算符,将文件中的数据读入buf(读完返回false)
	//	cout << buf << endl;//在显示屏上输出buf
	//ifs.close();

	第二种读取
	//char buf[1024] = { 0 };
	//while (ifs.getline(buf, sizeof(buf)))//一行一行读,读到buf中,buf容量为sizeof(buf)
	//	cout << buf << endl;//在显示屏上输出buf
	//ifs.close();

	//第三种读取
	string buf;
	while (getline(ifs, buf))//这里的getline是全局函数
		cout << buf << endl;
	ifs.close();

	第四种读取(一个字符一个字符的读,效率不如前3种,不推荐)
	//char c;
	//while ((c = ifs.get()) != EOF)//EOF表示文件尾
	//	cout << c;
	//ifs.close();

}

int main()
{
	test01();
	test02();
	system("pause");
}

你可能感兴趣的:(c++)