文件操作包括准备+后勤工作,和正式的读写工作。
1. 准备+后勤工作
准备+后勤就是打开文件、关闭文件。
使用 Cpp 的文件操作的时候,要包含头文件:#include <fstream>
1.1 打开文件:
- 可以调用 .open() 方法;
- 也可以采用字符串初始化的方式打开。
//打开文件方式1:.open()方式
//0- 定义一个输出文件流对象
//ofstream out_file;
//1- 打开文件
//out_file.open("test.txt");
//打开文件方式2:字符串(文件路径)初始化方式
string filename("./testdir/test.txt");
ofstream out_file(filename); //对于作为输入的文件:ifstream in_file(filename);
//打开文件成功与否的检查
if(!in_file)
{
cerr << "file open failed!" << endl;
}
1.2 关闭文件
调用 close()方法。
in_file.close();
2. 读写工作
读写工作就像使用 cin, cout 一样使用 fstream。
2.1 读操作(此时,文件作为输入 ifstream)
#if 1
//方式1: getline()
string strbuf;
while(getline(in_file, strbuf))
{
cout << strbuf << endl;
}
#else
//方式2:>> 操作符
string testbuf;
while(in_file >> testbuf)
{
cout << testbuf << endl;
}
#endif
2.1 写操作(此时,文件作为输入 ofstream)
//使用操作符:<<
out_file << "Zhao|25|Male" <<endl
<< "Qian|24|FeMale" <<endl
<< "Sun|30|Male" <<endl;