写入文本文件而不覆盖它
我正在用 C++ 进行重力数值模拟,我想在每次计算一步时备份我的结果。
但是,按照我现在的方式,程序总是会覆盖该文件。我想我可以通过始终将文本保存在不同的文件或变量中来解决,但我想知道是否有一种更简单的方法来打开文本文件,这样我就不会覆盖它。
我当前的“备份代码”如下所示:
fstream log;
log.open ("log.txt");
if (log.is_open())
{...
...
log.close();
}
I'm doing a numerical simulation of gravity in C++ and I want to back up my results every time a single step is counted.
However, the way I do it now, the programm always overwrites the file. I guess I would be able to solve in by always saving the text in a different file or variable, but I wonder if there's an easier way to open a text file so that I wouldn't overwrite it.
My current "back-up code" looks like this:
fstream log;
log.open ("log.txt");
if (log.is_open())
{...
...
log.close();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
以附加模式打开流:
这将简单地将新输出附加到现有输出,从而为您提供一个随着时间的推移而增长的大日志文件。
一个建议(如果您还没有这样做)是在日志记录数据中包含某种时间戳,以便在读取文件时,可以将记录的数据与程序的运行相关联。
Open the stream in append-mode:
This will simply append the new output with the existing, giving you one big log file that grows over time.
One suggestion (if you're not doing it already) is to include some kind of timestamp in the logging data, so that when you're reading the file, you can correlate the logged data to a run of the program.
使用
log.open("log.txt", fstream::app)
附加到文件。请阅读此参考以获取更多信息。
如果您需要复杂的日志记录和时间戳机制,那么有一个有用的帖子关于 C++ 的日志框架。 Pantheios 得到了接受的答案。
Use
log.open("log.txt", fstream::app)
for appending to file.Read this reference for further info.
If you need a sophisticated mechanism for logging and timestamping, there's a useful SO post about logging frameworks for C++. Pantheios got the accepted answer.
由于作者似乎对建议的答案有疑问,我将添加另一个答案。
我想使用显式流
和
有时效果更好。虽然我不知道原因。
Since the autor seemed to have problems with the suggested answers I'll add another one.
I guess working with the explicit stream
and
sometimes works better. Although I don't know the reason.
设置追加模式。看看这个:
http://www.cplusplus.com/reference/iostream/fstream/open/
Set the mode to append. See this:
http://www.cplusplus.com/reference/iostream/fstream/open/