在 C++ 中的文件(日志文件)中添加新行 [英] Appending a new line in a file(log file) in c++
问题描述
我有一个日志记录功能,我有日志文件.现在每次运行程序时,我都希望以前写入的文件不应被删除,而应附加当前数据(日志文件中的内容)
I have a logging functionality and in this I have got log files. Now every time I run the program I want that previously written file should not get deleted and should be appended with the current data (what ever is there in the log file)
只是为了说明清楚,例如:我有一个日志文件 logging_20120409.log,它每天都保存时间戳.假设我运行我的项目,它会将当前时间戳写入其中.现在,如果我重新运行它,以前的时间戳将被替换.我不想要这个功能.我想要上一个时间戳和当前时间戳.
Just to make it clear for example: I have a log file logging_20120409.log which keeps the timestamp on a daily basis. Suppose I run my project it writes to it the current timestamp. Now if I rerun it the previous timestamp gets replaced with it. I do not want this functionality. I want the previous time stamp along with the current time stamp.
请帮忙
推荐答案
您想以追加"模式打开文件,因此它不会删除文件的先前内容.您可以通过在打开文件时指定 ios_base::app
来实现:
You want to open the file in "append" mode, so it doesn't delete the previous contents of the file. You do that by specifying ios_base::app
when you open the file:
std::ofstream log("logfile.txt", std::ios_base::app | std::ios_base::out);
例如,每次运行时,它都会在文件中多添加一行:
For example, each time you run this, it will add one more line to the file:
#include <ios>
#include <fstream>
int main(){
std::ofstream log("logfile.txt", std::ios_base::app | std::ios_base::out);
log << "line\n";
return 0;
}
所以,当你第一次运行它时,你会得到
So, the first time you run it, you get
line
第二次:
line
line
等等.
这篇关于在 C++ 中的文件(日志文件)中添加新行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!