你好亲爱的乐于助人的人
seekg()
我在使用类的功能时遇到了问题ifstream
。我的目标是从具有已知布局的文本文件中读出一个整数。将以下内容视为名为 Ph_Sn.cfg 的示例文件。
some random text bla bla
48 molecules of all types
much more text
and numbers etc etc
在实际程序中,我打开文件并执行多个任务,这些任务需要我在读出位置上跳跃一下。我已经跟踪了我的问题并创建了一个最小的工作示例,即下面的代码。
简而言之:通过调用函数来移动流游标会以seekg()
某种方式破坏流对象并使下一个 >> 运算符设置失败位。
#include <iostream>
#include<fstream>
using std::ifstream;
using std::cin;
using std::cout;
using std::endl;
using std::ios;
int skipline(ifstream&);
int main() {
char *file_name = "Ph_Sn.cfg";
ifstream file;
int input;
file.open(file_name);
skipline(file); //skipping a certain amount of lines (here: 1) since I know the file layout
const ifstream::streampos correctPosition = file.tellg(); //stream position before the integer I want to read
file>>input;
cout<<"Integer of interest: "<<input<<endl; //check if integer was read correctly
file.seekg(ios::beg); //revert to start of the file, just for demonstration in this example
skipline(file);
cout<<"good flag, failbit, badbit, eof = "<<file.good()<<" "<<file.fail()<<" "<<file.bad()<<" "<<file.eof()<<endl; //checking flags just for demonstration
file.seekg(correctPosition); //if this line is commented out, the second reading succeeds
cout<<"after seekg comparison tellg==correctPosition "<<(file.tellg()==correctPosition)<<endl; //after calling seekg the position is still correct
cout<<"after seekg: good flag, failbit, badbit, eof = "<<file.good()<<" "<<file.fail()<<" "<<file.bad()<<" "<<file.eof()<<endl; //checking again, still no errors
file>>input; //attempt to read out the integer again
cout<<"Integer of interest: "<<input<<endl;
cout<<"good flag, failbit, badbit, eof = "<<file.good()<<" "<<file.fail()<<" "<<file.bad()<<" "<<file.eof()<<endl; //the >> operator set the fail flag
cin>>input; //I don't want the console to close to see the output
return 0;
}
int skipline(ifstream &file)
{
int code;
if(!file)
return(0);
else
{
do
{
code=file.get();
}
while (code!=10);
}
return(1);//no error
}
编译代码并在我的 Ph_Sn.cfg 所在的目录中运行 .exe 文件会在控制台上显示以下输出:
Integer of interest: 48
good flag, failbit, badbit, eof = 1 0 0 0
after seekg comparison tellg==correctPosition 1
after seekg: good flag, failbit, badbit, eof = 1 0 0 0
good flag, failbit, badbit, eof = 0 1 0 0
Integer of interest: 0
如代码注释中所述,只需注释掉 file.seekg(correctPosition);
操作即可在第二次读取时给出正确的整数。
我试图找到类似问题的答案,但在大多数情况下,设置了 eof 标志并且通过调用file.clear()
. 可悲的是,这似乎对我没有帮助。我也找到了这篇文章,但我认为我的问题有所不同,因为(我错了吗?):
- Failbit 不是
seekg()
在 >> 操作符之后而是之后设置的 - 我的文件很小(一些 kb)
- 我正在以文本模式打开文件
我想知道问题是否不在于代码,而在于我的 Eclipse 设置。如果代码有效,如果独立编译,如果是这样,什么样的设置可能导致这种(在我看来)奇怪的行为,我想有一个确认。我正在运行 32 位 Windows 操作系统、带有 cdt 插件的 eclipse-Luna 和 MinGW GCC 工具链。
我感谢任何形式的帮助或提示。到现在为止,这个问题已经占据了我整整一周的时间。