到达结束后,如何附加到std :: fstream(std :: fstream :: eof()是真的)

发布于 2025-01-23 17:20:31 字数 675 浏览 3 评论 0原文

我打开一个这样的文件(因为它是练习的一部分,可能需要覆盖文件):

#include <fstream>            //std::fstream.
std::fstream file("file.txt", std::ios::in | std::ios::out);

假设我已经读了一个文件直到末尾(到达文件的末尾)。

std::string tmp_buff;
while(std::getline(file, tmp_buff)) {}
file.seekp(file.tellg());

现在,我已经到达流的结尾,如何从这里附加到文件。因为如果我只是尝试定期写入,它将失败(实际上不会写):

file << "Text";

唯一的解决方案我发现的是在文件末尾重新打开文件:

if(file.eof())
    {
        file.close();
        file.open("file.txt", std::ios::in | std::ios::out | std::ios::app);
        file << '\n';
    }

任何帮助都将是感谢。

I open a file like this (Because it's part of an exercise and it may require overwriting the file):

#include <fstream>            //std::fstream.
std::fstream file("file.txt", std::ios::in | std::ios::out);

And let's say I have read a file until the end (To get to the end of the file).

std::string tmp_buff;
while(std::getline(file, tmp_buff)) {}
file.seekp(file.tellg());

Now I have got to the end of the stream, How do I append to the file from here. Because if I just try to write like regularly, it will fail (It will not actually write):

file << "Text";

The only solution I have found is to reopen the file at the end of the file:

if(file.eof())
    {
        file.close();
        file.open("file.txt", std::ios::in | std::ios::out | std::ios::app);
        file << '\n';
    }

Any help would be appreciated.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

乖乖哒 2025-01-30 17:20:31

首先,无需陈述std :: ios :: in and std :: ios :: Out使用fstream,因为它们是否存在构造函数中的默认值。 (实际上是std :: ios_base :: in/out更准确。 >)从std :: ios_base)继承
因此,std :: fstream文件(文件名)工作相同。

这里的问题是C ++流的工作原理。
当完全读取文件时,设置了eofbit。之后,另一个读数会触发failbit,因为没有什么可读取的,并且流的bool转换操作员返回false,然后退出循环。

bits 将继续保持直到清除为止。当它们打开时,该流不做任何事情。
因此,要清除他们:

file.clear();

将完成工作。之后您可以使用流。

First, there is no need to state std::ios::in and std::ios::out when using a fstream because they are there the default value in the constructor. (it is actually std::ios_base::in/out to be more exact. std::ios (std::basic_ios<char>) inherits from std::ios_base)
So std::fstream file(filename) works the same.

The problem here is how C++ streams work.
When the file is read completely, the eofbit is set. After that, another reading happens which will trigger the failbit because there is nothing to read and the stream's bool conversion operator returns false and it exits the loop.

The bits will stay on until they are cleared. And while they are on, the stream doesn't do anything.
So to clear them:

file.clear();

Will do the work. You can use the stream after that.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文