关于ifstream在c ++中的seekg()函数的问题? [英] Question about seekg() function of ifstream in C++?
本文介绍了关于ifstream在c ++中的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);
返回到文件的开头,但它不工作?
任何人都可以帮助我吗?
感谢
In the above code, I want to read the file then moving the pointer to the beginning of the file and read again.
I have used inFile.seekg(0, ios::beg);
to get back to the beginning of the file but it does not work?
Can anyone help me, please?
Thanks
推荐答案
在寻找开始之前,您需要清除所有错误标志,否则不执行任何操作在流上:
Before you seek to the beginning, you need to clear all error flags, else no operations are done on the stream:
inFile.clear();
inFile.seekg(0,std::ios::beg);
这是因为 eof
,因为您到达文件的结尾。
That's because the eof
bit will be set, because you reached the end of the file before.
这篇关于关于ifstream在c ++中的seekg()函数的问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文