示例


切记:需要引入头文件 fstream

读入操作

写入操作

  1. #include <iostream>
  2. #include <fstream>
  3. using namespace std;
  4. int main(){
  5. fstream fp("test.txt",ios::in | ios::out);
  6. if(!fp){
  7. cout << "open file failed" << endl;
  8. return 0;
  9. }
  10. fp << "WelcomeToMyHome!";
  11. static char str[100];
  12. fp.seekg(ios::beg);//使文件指针指向文件头
  13. fp >> str;
  14. cout << str << endl;
  15. fp.close();
  16. return 0;
  17. }

获取文件总大小

  1. fp.seekg(0, fp.end);
  2. size_t srcSize = fp.tellg();
  3. fp.seekg(0, fp.beg);

fstream 参数

模式标志 描述
ios::app 追加模式。所有写入都追加到文件末尾。
ios::ate 文件打开后定位到文件末尾。
ios::in 打开文件用于读取。
ios::out 打开文件用于写入。
ios::trunc 如果该文件已经存在,其内容将在打开文件之前被截断,即把文件长度设为 0。

文件位置指针

seekg

seekg函数官方解释为:

  1. basic_istream& seekg( pos_type pos );

表示从ios::beg,也就是开始的位置往后偏移pos个单位

  1. basic_istream& seekg( off_type off, std::ios_base::seekdir dir);

off:为偏移量,为正时表示向后偏移,为负时表示向前偏移
dir:为起始位置,分为 ios::beg ios::cur ios::end 三种

使用例子:

  1. // 定位到 fileObject 的第 n 个字节(假设是 ios::beg)
  2. fileObject.seekg( n );
  3. // 把文件的读指针从 fileObject 当前位置向后移 n 个字节
  4. fileObject.seekg( n, ios::cur );
  5. // 把文件的读指针从 fileObject 末尾往回移 n 个字节
  6. fileObject.seekg( n, ios::end );
  7. // 定位到 fileObject 的末尾
  8. fileObject.seekg( 0, ios::end );

解决C++中用eof()多读一次

在C++中文件的读取时,如果用
ifstream fin(“xxx.xxx”);
while(!fin.eof())
{…}时总是会出现多读一次,那么这时我们只要用
while(fin.peek() != EOF)就可以解决。peek()是文件流中用来读取文件指针下一位置的值,但指针仍然在当前位置而不是跳到一下位置.