C++ 读取和写入二进制文件的大小
免责声明:这只是初学者的另一项任务,所以我很清楚,在不同的编译器和不同的体系结构上,我可能会得到不同的(不兼容的)二进制文件。所以它只在这个特定的机器上工作是可以的 我正在从二进制文件中写入和读取C++ 读取和写入二进制文件的大小,c++,C++,免责声明:这只是初学者的另一项任务,所以我很清楚,在不同的编译器和不同的体系结构上,我可能会得到不同的(不兼容的)二进制文件。所以它只在这个特定的机器上工作是可以的 我正在从二进制文件中写入和读取size\t。写作看起来像: std::string result; result.append((char *)&block_size_, sizeof(block_size_)); 然后不久,结果被写入一个文件 但当我以同样的方式阅读时: map_binary.copy((char *)&
size\t
。写作看起来像:
std::string result;
result.append((char *)&block_size_, sizeof(block_size_));
然后不久,结果
被写入一个文件
但当我以同样的方式阅读时:
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> ]
警告C4996:'std::basic_string::copy':带有可能不安全参数的函数调用-此调用依赖调用方检查传递的值是否正确。要禁用此警告,请使用-D_SCL_SECURE_NO_警告。有关如何使用VisualC++ ++检查迭代器的文档
1> 与
1> [
1> _Elem=char,
1> _Traits=std::char_Traits,
1> _Alloc=std::分配器
1> ]
1> c:\ProgramFiles(x86)\microsoft visual studio 11.0\vc\include\xstring(1777):请参阅“std::basic_string::copy”的声明
1> 与
1> [
1> _Elem=char,
1> _Traits=std::char_Traits,
1> _Alloc=std::分配器
1> ]
我不明白为什么这段代码不安全,除了假装没有任何问题(使用-D\u SCL\u SECURE\u no\u警告
)之外,我正在寻找解决方案
那么,我错过了什么
PS:现在我只使用标准库来学习C++,所以使用<代码> Boost 或其他东西的解决方案是不可接受的。
< P>你没有丢失任何东西。如果你把任何东西复制到一个指针上,VC++会非常热心地警告你。在这种情况下,不能保证您将获得正确的目的地大小。毕竟,您可能会编写这样的东西map\u binary.copy((char*)&block\u size\u4,offset)
然后使用64位编译器查找失败的代码
如果您对避免这种错误的能力感到满意,那么禁用或忽略警告。
所以,UHM,