当我们要完成文件的读写操作功能时,可以使用fopen, fread, fwrite读写文件。也可以使用ifstream读文件,用ofstream写文件,或者直接用fstream读写文件。
下面考虑一种情形,当用户接收到一个题目的时候,用户根据题号(假设每一道题目都对应唯一的题号),读取本地的exam.txt文件,分别读取每一行的内容,并判断是否与接收的题号相同。如果有相同的题号,则可以得到此题目的答案;如果没有,则将此题目和用户做的答案记录在exam.txt文件的最后一行。
[exam.txt]
3 A
15 D
11 C
2 E
6 F
12 C
...
注意:
(1) if( file ) is only right for ifstream and ofstream but not for fstream, and fstream should use if( file.fail() )
(2) sscanf(szBuffer,"%2d",&num);// read the first two character from szBuffer and convert it to %d format, then save it into num variable
(3) infile.clear();// to clear file stream buffer
(4) fstream file("exam.txt",ios::in|ios::out|ios::app);// note, append mode
(5) file.seekg(ios::end);// set input stream position to _Pos
随机读写文件
通过移动文件读写指针,可在文件指定位置进行读写。
输入流操作:
seekg(绝对位置);// 绝对移动,
seekg(相对位置,参照位置); // 相对操作
tellg();// 返回当前指针位置
输出流操作:
seekp(绝对位置);// 绝对移动,
seekp(相对位置,参照位置);// 相对操作
tellp();// 返回当前指针位置
参照位置:
ios::beg = 0// 相当于文件头
ios::cur = 1 // 相当于当前位置
ios::end = 2// 相当于文件尾
[1] 分别使用ifstream读文件和ofstream写文件
[2] 只使用fstream完成读写文件