c++ - 将 fwrite 转换为 C++ 类型代码以写入二进制文件
问题描述
我正在尝试将 C 样式文件 IO 转换为 C++ 样式文件 IO。我需要将数字 42 写为 4 字节有符号整数。
这是我尝试过的 C 类型 IO 的示例
#include <stdio.h>
#include <string>
#include <fstream>
using namespace std;
int main()
{
FILE *myFile;
myFile = fopen ("input_file.dat", "wb");
int magicn = 42;
fwrite (&magicn, sizeof(magicn), 1, myFile);
fclose (myFile);
return 0;
}
我正在尝试根据我提出的另一个问题的建议将上述代码转换为 C++ 类型 IO(如何使用 fwrite 将带有填充的字符串写入二进制文件?)。
这是我的尝试:
#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;
int main()
{
ofstream myFile ("input_file.dat", ios::binary);
int magicn = 42;
myFile << setw(sizeof(magicn)) << magicn;
myFile.close();
return 0;
}
但是,当我使用 'xxd -b input_file.dat' 命令时,我期望的输出并不相同。
我期待的输出是(使用 C 类型 IO 代码生成)
0000000: 00101010 00000000 00000000 00000000 *...
但我看到了(我尝试使用 C++ 类型 IO 代码生成)
0000000: 00100000 00100000 00110100 00110010 42
寻找解决方案。感谢帮助!
解决方案
您当前的方法更像fprintf(myFile, "%d", magicn)
. 也就是说,它对流执行格式化插入,因此您最终会得到第 42 个 ASCII 字符的 ASCII 代码。
的类似物fwrite
是ostream::write
。只需查看可用的成员,ostream
即可了解您可以使用它做什么。
推荐阅读
- database - 在我的 oracle DB 表中有 21 个索引,是好是坏
- postgresql - 删除重复项的最有效方法 - Postgres
- laravel - Laravel 模型属性返回 0
- php - 如何在 CakePHP 2 中为 3 个树状连接表保存数据
- ruby-on-rails - 哈希和符号之间的混淆
- python - 如何使用已编译的正则表达式和/或列表理解为机器学习管道准备文本?
- java - 使用 java8 流从内部列表中检索数据
- node.js - 找不到 dist 文件
- google-app-engine - Google App Engine 标准 - 作曲家更新 --lock | 允许的内存大小用尽 | 错误 255
- c++ - 使用派生类 y 基模板的结构