到达结束后,如何附加到std :: fstream(std :: fstream :: eof()是真的)
我打开一个这样的文件(因为它是练习的一部分,可能需要覆盖文件):
#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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先,无需陈述
std :: ios :: in
andstd :: ios :: Out
使用fstream
,因为它们是否存在构造函数中的默认值。 (实际上是std :: ios_base :: in/out
更准确。 >)从std :: ios_base
)继承因此,
std :: fstream文件(文件名)
工作相同。这里的问题是C ++流的工作原理。
当完全读取文件时,设置了
eofbit
。之后,另一个读数会触发failbit
,因为没有什么可读取的,并且流的bool转换操作员返回false,然后退出循环。bits 将继续保持直到清除为止。当它们打开时,该流不做任何事情。
因此,要清除他们:
将完成工作。之后您可以使用流。
First, there is no need to state
std::ios::in
andstd::ios::out
when using afstream
because they are there the default value in the constructor. (it is actuallystd::ios_base::in/out
to be more exact.std::ios
(std::basic_ios<char>
) inherits fromstd::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 thefailbit
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:
Will do the work. You can use the stream after that.