读取和写入size_t到二进制文件
Reading and writing size_t to a binary file
免责声明:这只是初学者的另一个任务,因此我对在不同的编译器和不同体系结构上可能会得到不同(不兼容的)二进制文件的事实很好。因此,可以只能在这台特定的机器上使用。
我正在写和读取二进制文件的 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位编译器。
如果您对避免这种错误的能力感到满意,请禁用或忽略警告。
相关文章:
- 正在读取二进制文件(is_open)
- 在C++中将类(带有Vector成员)保存为二进制文件
- 如何从二进制文件中读取字符串
- 保存/加载大量短数组到二进制文件
- 从二进制文件中读取整数数组
- Android 在编译二进制文件时重建静态库
- 在 C++ 中将双精度变量写入二进制文件
- clang 的 libFuzzer 可以在同一二进制文件中测试超过 1 个 API 吗?
- C++:实际上不是从二进制文件中读取
- 如何从二进制文件中的给定符号中获取调用程序图
- 将内部带有矢量的结构保存/读取到二进制文件中
- 编译多个C++文件.调用二进制文件以运行代码
- 如何使用位字段将数据从二进制文件复制到结构中?
- uint8_t同一二进制文件的不同十进制值
- C++单个生成文件多个二进制文件
- 尝试将数字写入二进制文件时引发异常
- C++中读/写二进制文件
- 如何忽略某些二进制文件的执行?
- 对在不同二进制文件中创建的对象文件的依赖关系
- 我的 SDL2 程序需要哪些二进制文件,以便它在另一台未安装 SDL2 的计算机中工作