C++複数ファイルの連続読み書き
1970 ワード
C++複数ファイルの連続読み書き
同じfstreamオブジェクトfileで異なるファイルを連続的に読み書きすると、読み書きの次のファイルは、前のファイルを読み書きしたfileの状態に関連付けられます.
例とコードは次のとおりです.
ここでfinは最初のファイルをファイルの最後に読み込み、eofに遭遇し、finの状態をクリーンアップしていない場合、finの残留状態は次のファイルの読み取りに影響します.
削除したらclear()のうち2箇所fin.eof()はいずれも状態値1を返し、そうでなければ、最初のfin.eof()は1を返し、2番目は0を返します.
Open()関数のプロトタイプ:
参照先:http://www.cplusplus.com/reference/fstream/fstream/open/
http://blog.csdn.net/sutaizi/article/details/5068602
同じfstreamオブジェクトfileで異なるファイルを連続的に読み書きすると、読み書きの次のファイルは、前のファイルを読み書きしたfileの状態に関連付けられます.
例とコードは次のとおりです.
#include
#include
#include
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の残留状態は次のファイルの読み取りに影響します.
削除したらclear()のうち2箇所fin.eof()はいずれも状態値1を返し、そうでなければ、最初のfin.eof()は1を返し、2番目は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.csdn.net/sutaizi/article/details/5068602