【问题标题】:File output overwrites first line - C++文件输出覆盖第一行 - C++
【发布时间】:2015-03-14 10:15:46
【问题描述】:

我正在为我的程序创建一个简单的日志记录系统。我有一个函数,每当在我的程序的成员函数中调用时都会输出,这样每当采取行动时,它就会被记录到一个文本文件中。但是,当我希望将每个操作记录在新行上时,它似乎每次都会覆盖文件的第一行。

void Logger::log(int level, std::string message, std::string source)
{
    time_t rawtime;
    struct tm * timeinfo;
    char buffer[80];

    time (&rawtime);
    timeinfo = localtime(&rawtime);

    strftime(buffer,80,"%d-%m-%Y %I:%M:%S",timeinfo);
    std::string str(buffer);

    std::ofstream fout(source);
    if (fout.is_open())
    {
        fout<<"Logging Level: "<<level<< " - "  << str <<" - " << message <<std::endl;
        fout<<"test"<<std::endl;
        fout.close();
    }
}

无论调用多少次,记录器都只会(正确地)输出最后执行的操作。谁能让我知道为什么这不起作用?

文件输出:

Logging Level: 1 - 15-01-2015 09:13:58 - Function called: grow()

test

日志调用示例:

arrayLogger.log(1, "Function called: writeOut()", "logger.txt");

【问题讨论】:

  • 根据en.cppreference.com/w/cpp/io/basic_filebuf/open,如果你调用std::ofstream的构造函数,它将调用默认实现,它的open_mode设置为out,你可以看到总是丢弃任何已经存在的内容存在于文件中。你应该用out | app打开它。
  • 非常感谢你们俩,以后会记得的!

标签: c++ file logging output newline


【解决方案1】:

您每次都打开文件进行写入,这会覆盖所有现有内容。您应该(a)在该函数之外打开文件,可能通过使 ofstream 对象成为类成员,然后您的函数将简单地附加到它,或者(b)打开文件以进行附加,如下所示:

std::ofstream fout(source, std::ofstream::out | std::ofstream::app);

【讨论】:

  • std::ofstream::binary(我认为是名字)也可以使用,因为Windows可能会改变处理事物的行为(即使是为了阅读,也应该添加它以保持完整性)。
  • 我认为您不希望将文件作为二进制文件打开,以允许 std::endl 为平台进行适当的翻译,特别是因为 OP 没有将文件作为二进制文件打开,显然没有任何问题。为什么要引入更多复杂性?无论如何,这都不是重点。
  • 哦,天哪,真的,我从不同的问题转移了二进制文件的想法。很抱歉。
猜你喜欢
  • 2016-11-19
  • 1970-01-01
  • 1970-01-01
  • 2014-06-07
  • 1970-01-01
  • 2019-06-02
  • 2023-03-17
  • 2014-12-22
相关资源
最近更新 更多