c++文件读写

  1. fstream提供了三个类,用来实现c++对文件的操作(文件的创建、读、写)
    1. ifstream -- 从已有的文件读入
    2. ofstream -- 向文件写内容
    3. fstream - 打开文件供读写
  2. 文件打开模式
    1. ios::in             只读
      
      ios::out            只写
      
      ios::app            从文件末尾开始写,防止丢失文件中原来就有的内容
      
      ios::binary         二进制模式
      
      ios::nocreate       打开一个文件时,如果文件不存在,不创建文件
      
      ios::noreplace      打开一个文件时,如果文件不存在,创建该文件
      
      ios::trunc          打开一个文件,然后清空内容
      
      ios::ate            打开一个文件时,将位置移动到文件尾
  3. 文件指针位置在c++中的用法:
    1. ios::beg   文件头
      
      ios::end   文件尾
      
      ios::cur   当前位置
      file.seekg(0,ios::beg);   //让文件指针定位到文件开头 
      
      file.seekg(0,ios::end);   //让文件指针定位到文件末尾 
      
      file.seekg(10,ios::cur);   //让文件指针从当前位置向文件末方向移动10个字节 
      
      file.seekg(-10,ios::cur);   //让文件指针从当前位置向文件开始方向移动10个字节 
      
      file.seekg(10,ios::beg);   //让文件指针定位到离文件开头10个字节的位置

      //注意:移动的单位是字节,而不是行
  4. 常用的错误判断方法:
    1. s.good();    
      //如果流 s 处于有效状态,返回 true 。如果达到文件末尾,或者类型不匹配,或
      //者文件打开失败,返回 false 
      
      s.bad();  // 如果流 s 处于无效位(badbit置位) ,返回 true
      
      s.eof();  // 到达文件尾
  5. 常见用法
    1. #include<iostream>
      #include<algorithm>  
      //#include<stdio.h>
      #include<string>
      #include<vector>
      #include<fstream>
      using namespace std;
      int main(){
          ifstream fr;
          ofstream fw;
          fr.open("testData.txt",ios::in);
          fw.open("writeFile", ios::app);
          //cout << fr.is_open() << endl;   判断文件是否成功打开
          string s ;
          char ch[100];
          while (!fr.eof()){ //判断文件是不是到达末尾
              //fr>>s   碰到空格,制表符,换行符结束
              //fr.getline(ch, 100);  //读取一行,读到字符数组中去
              getline(fr, s);           // 读取一行,读到字符串中。
              fw << s<<endl;     //输出到文件
          }
          fw.close();
          fr.close();
          return 0;
      
      }

posted on 2020-01-11 22:15  哆啦只是个梦哦  阅读(133)  评论(0编辑  收藏  举报

导航