[置顶] C++文件流操作

      C++的文件流本质是利用了一个buffer中间层,有点类似标准输出和标准输入一样。

      需要包含的头文件:fstream.h

      需要的命名空间:std


      fstream提供了三个类,用来实现C++对文件的操作,以下对其做个简要概述。

      1.ifstream类:

      2.ofstream类:

      3.fstream类:


      支持的文件类型:文本文件和二进制文件(文本文件保存的是可读的字符, 而二进制文件保存的只是二进制数据。利用二进制模式,你可以操作图像等文件。用文本模式,你只能读写文本文件,否则会报错!)。

      举例如下:

       1.C++文件流操作之文件写入:

#include <fstream> 
#include <iostream>   
using namespace std;

int main(){  
      string str; 
      ofstream out; 
      out.open("d.txt");  
      str="This is an ofstream test program!\n";  
      out<<str<<endl;
      out.close();
      return 0;   
}

      2.C++文件流操作之文件读取

#include <fstream>
#include <iostream> 
using namespace std;

int main(){
      ifstream in;
      in.open("a.txt");
      for(string str;getline(in,str);)
          cout<<str<<"\n";
      in.close();
      return 0;
}

你可能感兴趣的:([置顶] C++文件流操作)