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

时间:2012-10-18 09:16:37

标签: c++

免责声明:这只是初学者的另一项任务,所以我很擅长在不同的编译器和不同的架构上,我可能会得到不同的(不兼容的)二进制文件。所以它可以只在这台特定的机器上运行。

我正在编写并从二进制文件中读取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.0\vc\include\xstring(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或其他内容的解决方案是不可接受的。

1 个答案:

答案 0 :(得分:1)

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

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

相关问题