首页 > 解决方案 > 将 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

寻找解决方案。感谢帮助!

标签: c++integerbinaryfilesfwrite

解决方案


您当前的方法更像fprintf(myFile, "%d", magicn). 也就是说,它对流执行格式化插入,因此您最终会得到第 42 个 ASCII 字符的 ASCII 代码。

的类似物fwriteostream::write。只需查看可用的成员,ostream即可了解您可以使用它做什么。


推荐阅读