C++连续读写多个文件

                                                                                                   C++连续读写多个文件

当用同一个fstream对象file连续读写不同的文件时,读写下一个文件会和读写上一个文件的file的状态相关联。

示例和代码如下:

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

int main () {
  fstream fin, fout;
  string str;
  
  //fstream::in|fstream::out
  fin.open( "1.txt", fstream::in );
  fout.open( "2.1.txt", fstream::out );
  
  while( fin >> str )
    fout << str << endl;
  
  //status of fin
  cout << "end of file      " << fin.eof()  << endl;
  cout << "open file failed " << fin.fail() << endl; 
  
  fin.close();
  fout.close();
  //将fin.eof的状态清除掉
  fin.clear();
  
  fin.open( "2.txt", fstream::in );
  fout.open( "2.2.txt", fstream::out );
  
  //status of fin
  cout << "end of file      " << fin.eof()  << endl;
  cout << "open file failed " << fin.fail() << endl;  
  
  while ( fin >> str )
        fout << str << endl;
        
  fin.close();
  fout.close();

  system( "pause" );
  return 0;
}


 

其中fin读取第一个文件到文件结尾,遇到eof,如果没有清理fin的状态,fin的遗留状态会影响读取下一个文件。

如果去掉fin.clear(),其中两处fin.eof()都会返回状态值1,否则,第一处fin.eof()返回1,第二处返回0。

open()函数原型:                            

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

filename形式:filename="2.txt" || filename="D:\\file\\2.txt"

参考:http://www.cplusplus.com/reference/fstream/fstream/open/

           http://blog.youkuaiyun.com/sutaizi/article/details/5068602

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值