简体   繁体   中英

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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