簡體   English   中英

文件輸出覆蓋第一行-C ++

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

即時通訊為我的程序創建一個簡單的日志記錄系統。 我有一個函數,只要在程序的成員函數中調用該函數,該函數就會輸出,以便每執行一個操作便將其記錄到文本文件中。 但是,當我希望每個動作都記錄在新行中時,它似乎每次都只會覆蓋文件的第一行。

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");

您每次都打開要寫入的文件,這會覆蓋所有現有內容。 您應該(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