读取和写入size_t到二进制文件

Reading and writing size_t to a binary file

本文关键字:二进制文件 size 读取      更新时间:2023-10-16

免责声明:这只是初学者的另一个任务,因此我对在不同的编译器和不同体系结构上可能会得到不同(不兼容的)二进制文件的事实很好。因此,可以只能在这台特定的机器上使用。

我正在写和读取二进制文件的 size_t。写作看起来像:

std::string result;
result.append((char *)&block_size_, sizeof(block_size_));

不久之后,result被写入文件。

但是,当我以相同的方式阅读它时:

map_binary.copy((char *)&block_size_, sizeof(block_size_), offset);

我得到警告

warning C4996: 'std::basic_string<_Elem,_Traits,_Alloc>::copy': Function call with parameters that may be unsafe - this call relies on the caller to check that the passed values are correct. To disable this warning, use -D_SCL_SECURE_NO_WARNINGS. See documentation on how to use Visual C++ 'Checked Iterators'
1>          with
1>          [
1>              _Elem=char,
1>              _Traits=std::char_traits<char>,
1>              _Alloc=std::allocator<char>
1>          ]
1>          c:program files (x86)microsoft visual studio 11.0vcincludexstring(1777) : see declaration of 'std::basic_string<_Elem,_Traits,_Alloc>::copy'
1>          with
1>          [
1>              _Elem=char,
1>              _Traits=std::char_traits<char>,
1>              _Alloc=std::allocator<char>
1>          ]

我无法明白为什么此代码不安全,并且在假装根本没有问题以外寻找解决方案(使用-D_SCL_SECURE_NO_WARNINGS)。

那么,我缺少什么?

ps:现在,我仅使用标准库学习C ,因此使用boost或其他内容的解决方案是无法接受的。

您不会缺少任何东西。如果您将任何内容复制到指针,VC 非常热衷于警告您。在这种情况下,不能保证您将获得正确的目的地大小。毕竟,您可能会编写类似map_binary.copy((char *)&block_size_, 4, offset);的内容,然后发现您的代码失败了64位编译器。

如果您对避免这种错误的能力感到满意,请禁用或忽略警告。