[英]ofstream writes null characters on a file in binary mode
We are facing an issue with device reboot.我们面临设备重启的问题。 We are running our application in linux os on a raspberry pi board.
我们正在树莓派板上的 linux os 中运行我们的应用程序。 We are maintaining a log file to which we are appending the records every 10sec with below code.
我们正在维护一个日志文件,我们每 10 秒使用以下代码将记录附加到该文件中。 One write can have one or more records in the pBuffer.
一次写入可以在 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;
}
We have observed that when we write the data and exactly on that time if we reboot the board(remove power), we are getting a record with complete NULL characters.我们已经观察到,当我们写入数据时,如果我们重新启动电路板(断开电源),我们会得到一个包含完整 NULL 字符的记录。 File size will be increased based on the record size, for example if we write 100 bytes file size will be header size(100) + old data size (100) + new data(100) = 300bytes.
文件大小将根据记录大小增加,例如,如果我们写入 100 字节,文件大小将为标头大小 (100) + 旧数据大小 (100) + 新数据 (100) = 300 字节。 When we try to read the file we are getting last 100 bytes full of NULL characters.
当我们尝试读取文件时,最后 100 个字节充满了 NULL 字符。
This will depend on the filesystem in use, but what is likely happening here is that the filesystem is committing the change to the file metadata (in this case, its length) before all the data is written.这将取决于正在使用的文件系统,但这里可能发生的情况是文件系统在写入所有数据之前提交对文件元数据(在这种情况下,它的长度)的更改。 If you require the file to be consistent even in case of a crash, and are using ext4, try mounting with the
data=journal
option.如果您要求文件即使在崩溃的情况下也保持一致,并且正在使用 ext4,请尝试使用
data=journal
选项进行挂载。 Note that this has performance impacts due to disabling delayed allocation.请注意,由于禁用延迟分配,这会影响性能。
- If the record is not written completely how the file size is increasing?
如果记录没有完全写入文件大小是如何增加的?
If null bytes are written, those increase file size just as much as any other byte.如果写入空字节,则这些增加的文件大小与任何其他字节一样多。
- How exactly the record is filled with NULL?
记录究竟是如何被 NULL 填充的?
It can potentially happens on the following line:它可能发生在以下行:
File.write(pBuffer, Size);
If pBuffer
contains null chars, then those null chars are written to the file.如果
pBuffer
包含空字符,则将这些空字符写入文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.