C++ 写入文本文件而不覆盖它

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4155537/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 14:38:46  来源:igfitidea点击:

Writing into a text file without overwriting it

c++textinputnumerical

提问by Tom83B

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.

我正在用 C++ 对重力进行数值模拟,每次计算一个步骤时,我都想备份我的结果。

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();
}

回答by unwind

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.

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

回答by darioo

Use log.open("log.txt", fstream::app)for appending to file.

使用log.open("log.txt", fstream::app)了附加到文件中。

Read thisreference for further info.

阅读参考资料以获取更多信息。

If you need a sophisticated mechanism for logging and timestamping, there's a useful SO postabout logging frameworks for C++. Pantheiosgot the accepted answer.

如果您需要一个复杂的日志记录和时间戳机制,有一个关于 C++ 日志记录框架的有用的 SO帖子Pantheios得到了公认的答案。

回答by caveman

Set the mode to append. See this: http://www.cplusplus.com/reference/iostream/fstream/open/

设置要追加的模式。看到这个:http: //www.cplusplus.com/reference/iostream/fstream/open/

回答by PascExchange

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.

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