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

时间:2011-05-13 01:46:40

标签: c++ file

我正在测试以下代码:

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);来回到文件的开头但它不起作用? 有人可以帮帮我吗? 感谢

3 个答案:

答案 0 :(得分:14)

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

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

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

答案 1 :(得分:5)

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

答案 2 :(得分:-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;

}