【发布时间】:2020-11-03 03:06:31
【问题描述】:
我们面临设备重启的问题。我们在树莓派板上的 linux 操作系统中运行我们的应用程序。我们正在维护一个日志文件,我们每 10 秒使用以下代码将记录附加到该文件中。一次写入在 pBuffer 中可以有一条或多条记录。
bool FileOP::Append(const std::string & PathName, const char * pBuffer, uint64_t Size)
{
bool AppendSuccessful = false;
std::ofstream File;
try
{
File.exceptions(std::ofstream::badbit | std::ofstream::failbit);
File.open(PathName.c_str(), std::ofstream::out | std::ofstream::binary | std::ofstream::app);
File.write(pBuffer, Size);
File.close();
AppendSuccessful = true;
}
catch (std::exception & e)
{
std::cout << "Error when appending string to file: " << PathName
<< std::strerror(errno) << " Exception : " << e.what() << std::endl;
}
return AppendSuccessful;
}
我们观察到,当我们写入数据时,如果我们重新启动板(断电),我们会得到一个包含完整 NULL 字符的记录。文件大小将根据记录大小增加,例如如果我们写入 100 字节,文件大小将是标题大小(100)+ 旧数据大小(100)+ 新数据(100)= 300 字节。当我们尝试读取文件时,最后 100 个字节充满了 NULL 字符。
- 如果记录未完全写入,文件大小如何增加?
- 究竟如何用NULL 填充记录?我们已验证写入的每条新记录都不包含 NULL 字符。
【问题讨论】:
标签: c++ linux fstream ofstream