gpt4 book ai didi

c++ - Linux下boost::interprocess::create_or_open_file更改文件类型

转载 作者:太空宇宙 更新时间:2023-11-04 03:44:24 24 4
gpt4 key购买 nike

我正在移植源代码以打开/读取/写入在多个进程之间共享的文件。它在 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)

我在我读过的所有页面中都没有发现这个技巧!

关于c++ - Linux下boost::interprocess::create_or_open_file更改文件类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28701521/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com