文件输出覆盖第一行 - C++
File output overwrites first line - C++
im 为我的程序创建一个简单的日志记录系统。我有一个函数,每当在程序的成员函数中调用时都会输出,因此每当执行操作时,它都会记录到文本文件中。但是,当我希望每个操作都记录在新行上时,它似乎每次都会覆盖文件的第一行。
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);
相关文章:
- 用c++从输入文件中读取另一行
- 读取文件的最后一行并输入到链接列表时出错
- 我正在使用嵌套的while循环来解析具有多行的文本文件,但由于某种原因,它只通过第一行,我不知道为什么
- 从C++dll访问C#中的一行主要参数
- 在C++中,我如何接受不同于同一行的用户输入
- 如何从一行中读取特定数量的字符?(C++)
- 读取最后一行代码算法 - c++ 时出现问题
- 查找矩阵C++中每一列和每一行的最小和最大元素
- 有没有办法在一行中填充矢量图
- 需要将一行代码从C++ Qt翻译成PyQt
- 为什么如果我添加这一行,我的程序会不断询问值
- 如何使代码打印文本文件中的第一行?
- 如何在C++中以这种方式返回一行文本?
- 如何使用运算符在同一行中多次调用函数
- 如何格式化我的文本文件以使其不会一遍又一遍地重复同一行?
- 而(!inputfile.eof())只读取第一行?
- 这段代码的最后一行在做什么?
- 逐字读取文本文件中的每一行并转换为 int(无限循环或崩溃?
- C++找出覆盖同一行的数组
- 如何让字符数组在一行而不是多行中打印出来?