关于 ifstream 在 C++ 中的 seekg() 函数的问题

Question about seekg() function of ifstream in C++?

本文关键字:函数 问题 seekg ifstream C++ 中的 关于      更新时间:2023-10-16

我正在测试以下代码:

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);回到文件的开头,但它不起作用?请问谁能帮我?谢谢

在你寻找开始之前,你需要清除所有错误标志,否则不会对流执行任何操作:

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

这是因为将设置eof位,因为您之前到达了文件的末尾。

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

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;
}