读书人

怎样重新回到文件的开头?解决办法

发布时间: 2012-03-06 20:47:55 作者: rapoo

怎样重新回到文件的开头?
有以下代码:
string iName;
cin > > iName;
fstream file ( iName.c_str() );
if ( !file )
{
cout < < "open infile failed! ";
exit ( -1 );
}


当文件读取到一定位置,怎样重新回到文件的开头呢?

[解决办法]
// basic_istream_seekg.cpp
// compile with: /EHsc
#include <iostream>
#include <fstream>

int main ( )
{
using namespace std;
ifstream file;
char c, c1;

file.open( "basic_istream_seekg.txt " );
file.seekg(2); // chars to skip
file > > c;
cout < < c < < endl;

file.seekg( 0, ios_base::beg );
file > > c;
cout < < c < < endl;

file.seekg( -1, ios_base::end );
file > > c1;
cout < < c1 < < endl;
}
[解决办法]
ifstream ifs( "test.cpp " );
string str;
getline( ifs , str);
cout < <str < <endl;
ifs.seekg(0);//这样就可以了
getline( ifs , str);
cout < <str < <endl;

读书人网 >C++

热点推荐