在 C++ 中的文件(日志文件)中添加新行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10071137/
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-27 13:34:43  来源:igfitidea点击:

Appending a new line in a file(log file) in c++

c++fileappendinitwithcontentsoffile

提问by gandhigcpp

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)

我有一个日志功能,在这个我有日志文件。现在每次运行程序时,我都希望以前编写的文件不应该被删除,并且应该附加当前数据(日志文件中的内容)

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.

例如,为了清楚起见:我有一个日志文件 logging_20120409.log,它每天都保留时间戳。假设我运行我的项目,它会将当前时间戳写入其中。现在,如果我重新运行它,先前的时间戳将被替换。我不想要这个功能。我想要上一个时间戳和当前时间戳。

Please help

请帮忙

回答by Jerry Coffin

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::appwhen you open the file:

您想以“追加”模式打开文件,因此它不会删除文件的先前内容。您可以通过指定ios_base::app打开文件的时间来做到这一点:

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

The second time:

第二次:

line
line

and so on.

等等。

回答by Ivaylo Strandjev

Use something like:

使用类似的东西:

#include <fstream>
#include <iostream>
using namespace std;
int main() {
  ofstream out("try.txt", ios::app);
  out << "Hello, world!\n";
  return 0;
}

The ios:app option makes the output get appended to the end of the file instead of deleting its contents.

ios:app 选项使输出附加到文件的末尾,而不是删除其内容。

回答by WeaselFox

maybe you need to open the file with the append option. like this:

也许您需要使用附加选项打开文件。像这样:

FILE * pFile;
pFile = fopen ("myfile.txt","a");

or this :

或这个 :

fstream filestr;
filestr.open ("test.txt", fstream::app)