简体   繁体   English

文件输出覆盖第一行-C ++

[英]File output overwrites first line - C++

im creating a simple logging system for my program. 即时通讯为我的程序创建一个简单的日志记录系统。 I have a function that outputs whenever called in member functions of my program, so that whenever an action is taken it is logged into a text file. 我有一个函数,只要在程序的成员函数中调用该函数,该函数就会输出,以便每执行一个操作便将其记录到文本文件中。 However it only seems to overwrite the first line of the file each time, when I want each action recorded on a new line. 但是,当我希望每个动作都记录在新行中时,它似乎每次都只会覆盖文件的第一行。

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();
    }
}

Regardless of the number of times called, the logger only outputs (correctly) the last action taken. 无论调用多少次,记录器仅(正确地)输出最后执行的操作。 Can anyone let me know why this isn't working? 谁能告诉我为什么这不起作用?

File output: 文件输出:

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

test

log call example: 通话记录示例:

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

You're opening the file for writing each time, which overwrites any existing content. 您每次都打开要写入的文件,这会覆盖所有现有内容。 You should either (a) open the file outside of that function, possibly by making the ofstream object a class member, and then your function will simply append to it, or (b) open the file for append, like so: 您应该(a)可能通过使ofstream对象成为类成员来打开该函数之外的文件,然后您的函数将简单地追加到该文件,或者(b)打开该文件进行追加,如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM