【问题标题】:Appending a new line in a file(log file) in c++在 C++ 中的文件(日志文件)中添加新行
【发布时间】:2012-04-21 16:53:27
【问题描述】:

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

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

请帮忙

【问题讨论】:

  • 您需要分享您的代码,了解日志文件的打开位置和创建位置。

标签: c++ file append initwithcontentsoffile


【解决方案1】:

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

std::ofstream log("logfile.txt", std::ios_base::app | std::ios_base::out);

例如,每次运行时,它都会在文件中多添加一行:

#include <ios>
#include <fstream>

int main(){
    std::ofstream log("logfile.txt", std::ios_base::app | std::ios_base::out);

    log << "line\n";
    return 0;
}

所以,第一次运行它时,你会得到

line

第二次:

line
line

等等。

【讨论】:

    【解决方案2】:

    使用类似的东西:

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

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

    【讨论】:

      【解决方案3】:

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

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

      或者这个:

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

      【讨论】:

      • 如果我有类似的东西:- file.open(logfileName.c_str());并且文件是 ofstream 的对象。
      • 比使用 fstream::app 选项。 file.open(logfileName.c_str(),fstream::app);
      • hmmm 使用了 file.open(logfileName.c_str(),ios::app);但是我需要知道内容不在不同的行中如果我要求它们在不同的行中怎么办跨度>
      • @gandhigcpp - 与 fstream 继承自 ios 相同。
      • :没关系,但是如果我想要不同行/新行中的东西,如果内容不是有序的,我需要做什么
      猜你喜欢
      • 2023-03-25
      • 2013-10-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多