对文件操作需要包含头文件<fstream> 文件类型:

  • 文本文件:文件以文本的ascii码形式存储在计算机中
  • 二进制文件:文件以二进制形式存储在计算机中

文件操作三大类:

  • ofstream:写操作(output to file)
  • ifstream:读操作(input from file)
  • fstream: 读写操作

写文件

  • 创建流对象

      ofstream ofs;
    
  • 打开文件

      ofs.open("xxx.txt",打开方式)
    
  • 写数据

      ofs<<"xxxx";
    
  • 关闭文件

      ofs.close();
    
  • 打开方式:

  1. ios::in 为读文件而打开文件
  2. ios::out 为写文件而打开文件
  3. ios::ate 初始位置:文件尾
  4. ios::app 追加方式写
  5. ios::trunc 如果文件存在,先删除再创建
  6. ios::binary 二进制方式 多个打开方式之间用|

读文件

    #include <fstream>
    
    ifstream ifs;
    ifs.open("text.txt",ios::in);
    if(!ifs.isopen()){
    	cout<<"文件打开失败!"<<endl;
        return;
    }
    
    //1.
    char buf[1024]={0};
    while(ifs>>buf){
    	cout<<buf<<endl;
    }
    
    //2.
    char buf[1024]={0};
    while(ifs.getline(buf,sizeof(buf))){
    	cout<<buf<<endl;
    }
    
    //3.
    string buf;
    while(getline(ifs,buf)){
    	cout<<buf<<endl;
    }
    
    //4.
    char c;
    while((c=ifs.get())!=EOF){//没有读到文件尾:end of file
    	cout<<c;
    }
    
    ifs.close();
    

以二进制方式操作文件

函数原型:ostream& write(const char* buffer,int len)

   #include <ostream>
   #include <fstream>
   
   class person{
   public:
       char name[64];//在对二进制文件操作时最好不要用c++中的string
       int age;
   };
   
   void test(){
       //写入
       ofstream ofs;
       ofs.open("person.txt",ios::out|ios::binary);
       person p={"hh",12};
       ofs.write((const char)*p,sizeof(person));
       ofs.close();
       
       //读出
       ifstream ifs;
       ifs.open("person.txt",ios::in||ios::binary);
       if(!ifs.isopen()){
           cout<<"failed."<<endl;
           return;
       }
       Person p2;
       ifs.read((char *)&p2,sizeof(person));
   }