到达eof后,文件处理无法使用fstream

File handling not working with fstream after reaching eof?

本文关键字:fstream 处理 eof 文件 到达      更新时间:2023-10-16

根据您的建议,我已经按照您的建议更改了代码,但当ios::out替换为ios::ate时,仍然存在问题。文件中没有写入任何内容(写入不起作用)。有没有什么方法可以检查下一个比特是否为eof,而不是读取它然后检查它?按照你的建议。有时当我处理文件时,它会显示文件指针的位置为-1,这意味着什么???

代码:

int main ()
{
    char p[80];
    fstream file("text1.txt",ios::out|ios::in); //if ios::ate is added here it results into infinite loop
    cout<<"Starting position of the file is "<<file.tellg()<<endl;
    getch();
    if(file.is_open())
        cout<<"file is openn";
    else
        cout<<"file is not openn";
    getch();
    file.seekp(0);
    while(file>>p)
    {
        cout<<p<<endl;
    }
    file.clear();
    cout<<"nThe current position of the file pointer is "<<file.tellg()<<endl;
    file.seekp(0);
    if(file.eof())
        cout<<"n the eofn";
    while(file>>p)
    {
        cout<<p<<endl;
    }
    file.close();
    return 0;
}

输出:

Starting position of the file is 0
file is open
Hello
man
how
are
you
The current position of the file pointer is 21
Hello
man
how
are
you

当这种从文件读取到文件末尾时,会导致设置eof和failbit。之所以设置Failbit,是因为在file.eof()条件下创建读取循环并不表示下一次读取将是流的末尾。它只是说我们还没有达到eof,所以使用:

while(file.eof())
{
file >> p;
}

最后一次读取可能只是eof,我们将处理未初始化的数据。如果发生这种情况,p内部将不会提取任何字符,并且将设置eof和fail标志。

当使用c++98时,需要使用将故障位重置为false

file.clear();

为了避免读取错误的情况,您应该在条件为while(file >> p)时从文件中提取字符。我推荐这个或这个关于堆栈溢出的问题。

因此,正确的C++98代码应该是这样的:

while(file >> p)
{
  std::count << p << std::endl;
}
file.clear();
file.seekp(0);
while(file >> p)
{
  std::count << p << std::endl;
}
file.close();

我在Visual Studio 2013上测试了几次,每次都有效。

考虑ios::ate模式:ios::outios::in是说明如何打开有问题的文件的修饰符。若要从文件中读取内容,则需要使用ios::out标志,而要进行写入,则需要用到ios::in

另一方面,ios::ate只是告诉编译器打开文件并立即转到文件的末尾。所以,若你们用ios::ate代替ios::out,那个么写入是不可能的,并且程序将在file << "Hello...";上升起失败标志。如果您只想附加数据,但从文件的开头读取,则应该使用ios::app,因为它告诉在每次写入之前查找eof。