2011-05-13 64 views
1

我测试下面的代码:关于在C++中ifstream的seekg()函数的问题?

int _tmain(int argc, _TCHAR* argv[]) 
{ 
    int sum = 0; 
    int x; 
    ifstream inFile; 

    inFile.open("test.txt"); 
    if (!inFile) { 
     cout << "Unable to open file"; 
     exit(1); // terminate with error 
    } 

    while (inFile >> x) { 
     cout << x << endl; 
    } 
    cout << "-----------------------------" << endl; 
    // Reading from beggining file again 
    inFile.seekg(0, ios::beg); 
    while (inFile >> x) { 
     cout << x << endl; 
    } 

    inFile.close(); 

    return 0; 
} 

在上面的代码,我想读文件,然后移动鼠标指针到文件的开头,然后再次读取。 我已经使用inFile.seekg(0, ios::beg);回到文件的开头,但它不起作用? 任何人都可以帮助我吗? 谢谢

回答

13

在你寻求一开始,你需要清除所有错误标志,否则没有操作上的数据流进行:

inFile.clear(); 
inFile.seekg(0,std::ios::beg); 

这是因为eof位将被设置,因为您已经达到结束之前的文件。

5

我认为你必须通过inFile.clear()重置ifstream的错误标志。否则它仍然认为它已经到达文件的末尾。

-2
int autoinc() //auto incriment no// 
{ 
    fstream fp; 

    fp.open("birthreg.dat",ios::in); 

    fp.seekg(0,ios::beg) ; **//what used this function** 

     int t=0; 

    while(fp.read((char*)&st,sizeof(birthreg))) 

    t=reg_no; 

    fp.close(); 

    return t; 

} 
+0

neg没有解释,奇怪的缩进,由于错误的注释语法,C风格的转换,什么是'reg_no',我可以继续编译。 – 2015-12-16 13:11:25