怎样重新回到文件的开头?解决办法
怎样重新回到文件的开头?
有以下代码:
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;
有以下代码:
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;