我正在移植源代码以打开/读取/写入在多个进程之间共享的文件。它在 Windows 下运行良好,因为它主要使用 boost::interprocess (1.44),我没想到会有太多问题,但我发现了一些奇怪的东西:
//pseudo code
namespace bip = boost::interprocess;
namespace bipd = boost::interprocess::detail;
loop
bip::file_handle_t pFile = bipd::create_or_open_file(filename, bip::read_write);
bipd::acquire_file_lock(pFile);
// try to read bytes from pFile with 'read'
bipd::truncate_file(pFile, 0);
bipd::write_file(pFile, (const void*)(textBuffer)), bufLen);
当代码第一次运行时,它会创建文件并写入文本。文件模式是 ASCII(ASCII 文本,行很长
),我可以读取文本。但是当循环运行第二次时,文件类型更改为
data
和 textBuffer
位于文件中,但作为二进制数据!
我检查了 boost/interprocess/details/os_file_functions.hpp
但没有找到该行为的原因。
你有什么想法吗?
终于找到解决办法了......看来,如果您位于文件末尾(::read
之后的文件指针位置),则在“boost::interprocess::detail::truncate_file”实现中使用的 ::ftruncate
函数会导致不正确的行为。
为了在 Linux 和 Windows 下保持相同的行为(将文件类型保持为 ASCII 文本),我使用了一个简单的 ::seek(id,0,SEEK_SET)
。
我在我读过的所有页面中都没有发现这个技巧!
我是一名优秀的程序员,十分优秀!