即時爲我的程序創建一個簡單的日誌記錄系統。我有一個函數,只要在我的程序的成員函數中調用就輸出,所以無論何時執行一個操作,它都會被記錄到一個文本文件中。但是,當我希望每個動作都記錄在新行中時,似乎每次都會覆蓋文件的第一行。文件輸出覆蓋第一行 - 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");
根據http://en.cppreference.com/w/cpp/io/basic_filebuf/open,如果你調用'std :: ofstream'的構造函數,它會調用默認的實現,它的open_mode設置爲' out「,正如你所看到的,將永遠放棄已存在於文件中的任何內容。你應該用'out |打開它app'。 – Creris
非常感謝你們倆,不要忘了將來! – user3027864