txt文件的读取,写入
步骤:
1.包含头文件
fstream
2.创建流对象
ofstream ofs 写
ifstream ifs 读
3.打开文件,判断是否成功
ofs.open(“text.txt”,ios::out)
text.txt为文件名
ios::in //读 ios::out//写 ios::binary//二进制
ios::binary|ios::out二进制写
ifs.is_open() 成功返回true,失败返回false
4.写数据/读数据
ofs << “hi” << endl; //写
char buf[1024] = { 0 }; //读
while (ifs >> buf)
{
cout << buf << endl;
}
5.关闭文件
ofs.close()
//写
ofstream ofs;
ofs.open("text.txt",ios::out);
ofs << "hi" << endl; ;
ofs.close();
//读
ifstream ifs;
ifs.open("text.txt", ios::in);
if (!ifs.is_open())
{
cout << "打开失败" << endl;
}
char buf[1024] = { 0 };
while (ifs >> buf)
{
cout << buf << endl;
}