gpt4 book ai didi

c++ - 在尝试读取仅为输出而打开的文件时,为流设置了 eofbit 标志。这是为什么?

转载 作者:太空狗 更新时间:2023-10-29 21:46:34 25 4
gpt4 key购买 nike

#include <iostream>
#include <fstream>

using namespace std;

int main()
{
fstream file("out.txt", ios_base::app);

file.seekg(0, ios_base::beg);

char buffer[100];

if( !file.getline(buffer, 99) )
cout << "file.failbit " << boolalpha << file.fail() << " file.eofbit " << file.eof()
<< '\n'
<< "file.badbit " << file.bad() << " file.goodbit " << file.good() << '\n';

}

输出

enter image description here

最佳答案

该标准禁止您读取仅为输出而打开的文件。来自 basic_filebuf 的第 27.9.1.1.3 段(fstream 的底层实现的一部分):

If the file is not open for reading the input sequence cannot be read.

因此,当尝试从仅为写入而打开的文件中读取时,人们会期望看到 failbit。该标准还指出,每当 getline 到达输入序列的末尾时,就会设置 eofbit。由于您实际上有一个空的输入序列(即您无法读取的文件),因此第一次调用 getline 也会设置 eofbit。在标准中,底层流缓冲区下溢basic_streambuf::underflow() 在失败时返回 traits::eof()(参见 27.6.3.4.3 第 7-17 段)。

要解决此问题,请将 ios_base::in 添加到文件的打开模式。

关于c++ - 在尝试读取仅为输出而打开的文件时,为流设置了 eofbit 标志。这是为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14776416/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com