写入文本文件而不覆盖它

发布于 2024-10-02 01:30:20 字数 268 浏览 0 评论 0原文

我正在用 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 技术交流群。

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

发布评论

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

评论(4

巷子口的你 2024-10-09 01:30:20

以附加模式打开流:

log.open("log.txt", fstream::app);

这将简单地将新输出附加到现有输出,从而为您提供一个随着时间的推移而增长的大日志文件。

一个建议(如果您还没有这样做)是在日志记录数据中包含某种时间戳,以便在读取文件时,可以将记录的数据与程序的运行相关联。

Open the stream in append-mode:

log.open("log.txt", fstream::app);

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.

三寸金莲 2024-10-09 01:30:20

使用 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.

雨的味道风的声音 2024-10-09 01:30:20

由于作者似乎对建议的答案有疑问,我将添加另一个答案。

ofstream log;
log.open("log.txt", ofstream::app);

我想使用显式流

ifstream

流媒体

有时效果更好。虽然我不知道原因。

Since the autor seemed to have problems with the suggested answers I'll add another one.

ofstream log;
log.open("log.txt", ofstream::app);

I guess working with the explicit stream

ifstream

and

ofstream

sometimes works better. Although I don't know the reason.

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