这章记录记录对文本文件和二进制文件的读写。
挂库#include
写文件的类 :ofstream ,读文件的类:ifstream 读写文件的类:fstream
1.文本文件
(1)写:①创建流对象(ifstream )②打开文件③写④关
ofstream ofs;
ofs.open("test.txt",ios::out|ios::app);
//
ofs << "hahahaha" << endl;
ofs << "xxixixi" << endl;
ofs.close();
(2)读:①创建流对象(ifstream )②打开文件③判断文件是否打开成功③读(四种方式)④关
ifstream ifs;
ifs.open("test.txt", ios::in);
//判断文件是否打开成功
if (ifs.is_open() != true)
{
cout << "文件打开失败" << endl;
return;
}
//第一种
//char buf[1024] = { 0 };
//while (ifs >> buf)
//{
// cout << buf << endl;
//}
//第二种
//char buf[1024] = { 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;
//}
ifs.close();
2.二进制文件
与上面差不多,只是写用write函数、读用read函数