C++语法基础--标准IO库--文件的输入和输出(fstream,ifstream,ofstream)

来源:互联网 发布:卖假货的淘宝足球鞋店 编辑:程序博客网 时间:2024/06/06 15:39
1.fstream
  *构造函数:
     default (1):
           fstream();
     initialization (2)
          explicit fstream (const char* filename,ios_base::openmode mode = ios_base::in | ios_base::out);
    eg:
       fstream out("f:/test.txt",ios::out);



  *open():
         void open (const char* filename,ios_base::openmode mode = ios_base::in | ios_base::out);
 

    eg:
         fstream out;
out.open("f:\\test.txt",ios::out);


  *检查文件打开是否成功
    eg:
     ofstream out("d:/test.txt");
      if(out)      
  //打开成功
       {
          ......   //do something
        }
   
  *close():
    void close();


  *clear():清除文件流的状态
       void clear( iostate state = goodbit );
   注:关闭流并不能改变流对象的内部状态
    
    
2.将文件流和新文件重新捆绑
   *必须先关闭当前的文件,然后才打开另一个文件
    eg:
        ifstream in("d:/test.txt");
in.close();
in.open("d:/test1.txt");





3.打开模式
   void open(const char* filename,int mode,int access);


 mode:
   ios::app:     以追加的方式打开文件
   ios::ate:     文件打开后定位到文件尾,ios:app就包含有此属性
   ios::binary:    以二进制方式打开文件,缺省的方式是文本方式。两种方式的区别见前文
   ios::in:      文件以输入方式打开(文件数据输入到内存)
   ios::out:     文件以输出方式打开(内存数据输出到文件)
   ios::trunc:    如果文件存在,把文件长度设为0


 access:
    文件的保护属性. 在 windows 平台可以取以下的值:


    #define _SH_DENYRW      0x10    /* deny read/write mode */
    #define _SH_DENYWR      0x20    /* deny write mode */
    #define _SH_DENYRD      0x30    /* deny read mode */
    #define _SH_DENYNO      0x40    /* deny none mode */
    #define _SH_SECURE      0x80    /* secure mode */

    eg:
       in.open("d:/test.txt",ios::in, 0x40);
//以写方式打开普通文件test.txt


 *所以文件都可以用ate,binary模式打开
 *out,trunc,app模式只用于ofstream,fstream关联的文件
 *in模式只用于ifstream,fstream关联的文件
 *ifstream默认以in模式打开
 *ofstream默认以out模式打开,并清空文件内容,如想保留数据,唯一的方法是指定为app模式打开


4.fstream对象既可以读也可以写与它关联的文件,默认以in和out模式打开


5.模式是文件的属性而不是流的属性


7.打开模式的组合解析
  out:          删除文件已有数据
  out|app       在文件尾写入,并不会删除文件已有数据
  out|trunc     同out
  in            打开文件做读操作
  in|out        打开文件做读,写操作,并定位于文件开头处,不会删除文件已有数据
  in|out|trunc        打开文件做读,写操作,删除文件已有数据
  以上所有模式组合都可以加ate,将文件定位于末尾处


8.关于文件打开方式的一些个人经验总结
    还记得刚学文件的输入和输出时,相同的代码打开文件总是有时运行成功,有时失败的。纠结了老半天也没找到原因,上网百度也没有人总结。
    因此,在这里把一般初学者容易纠结的问题总结一下。

     eg:
        fstream out;
out.open("f:/test.txt");

      解析:此种方式打开,如果f:盘下没有test.txt,则打开失败
      
      eg:
        fstream out;
out.open("f:/test95.txt",ios::out);

      解析:此种方式打开,无论f:盘下是否存在test.txt,都打开成功


    总结:只要是打开方式和输入有关(如:ifstream,fstream),必须确保指定的目录下存在相应的文件,否则打开失败
原创粉丝点击