追加在C在一个文件(日志文件)的新行++ [英] Appending a new line in a file(log file) in c++
问题描述
我有一个日志记录功能,并在此我有日志文件。现在,每当我运行程序时我想要的previously书面文件不应该被删除,并应与当前数据被追加(曾经是那里的日志文件)
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。假设我跑我的项目写入它的当前时间戳。现在,如果我重新运行它的previous时间戳被它取代。我不想要这个功能。我想previous时间戳与当前时间戳一起。
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.
请帮忙
推荐答案
您想打开追加模式下的文件,所以它不会删除该文件的previous内容。你通过指定的ios_base ::应用
当你打开文件:
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屋!