C++ 入门第 5 版第 17.5.3 章 fstream 没有添加新行

C++ primer 5th edition Chapter 17.5.3 fstream doesn't put new line

本文关键字:fstream 添加 新行 门第 版第 C++      更新时间:2023-10-16

这是C++入门第 5 版书籍第 17 章 (17.5.3( 中的示例代码。

int main(void) {
    fstream inOut("test.txt", fstream::ate | fstream::in | fstream::out);
    if (!inOut)
    {
        cerr << "Unable to open file!" << endl;
        return EXIT_FAILURE;
    }
    auto end_mark = inOut.tellg();
    inOut.seekg(0, fstream::beg);
    size_t cnt = 0;
    string line;
    while (inOut && inOut.tellg() != end_mark && getline(inOut, line))
    {
        cnt += line.size() + 1;
        auto mark = inOut.tellg();
        inOut.seekg(0, fstream::end);
        inOut << cnt;
        if (mark != end_mark)
        {
            inOut << " ";
        }
        inOut.seekg(mark);
    }
    inOut.seekg(0, fstream::end);
    inOut << "n";
    return 0;
}

文件test.txt的内容为:

abcd
efg
hi
j
<This is a blank new line>

关键是,如果此文件以空行结尾,则此代码将按预期工作。换句话说,它将文件更改为:

abcd
efg
hi
j
5 9 12 14
<This is a blank new line>

但是,如果文件没有以空白换行符结尾,它将输出如下:

abcd
efg
hi
j5 9 12 

请注意,此文件不以换行符结尾。我的问题是空白新行在哪里?毕竟,有代码

inOut << "n";

无论如何,它都应该放置一个新的空白行。哪里出了问题?

问题是,通过到达文件末尾,流的坏位被设置了。如果添加

inOut.clear();

在最后一个 inOut <<""之前,换行符按预期写入,尽管没有换行符的行长度仍然不会添加。