将fwrite转换为C ++类型代码以写入二进制文件

问题描述 投票:0回答:2

我正在尝试将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;
}

[我正在根据我问过的另一个问题(How to write a string with padding to binary file using fwrite?)的建议,将上述代码转换为C ++类型的IO。

这是我的尝试:

#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++ integer binaryfiles fwrite
2个回答
0
投票

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

fwrite的类似物是ostream::write。只需查看ostream的可用成员,即可找到可以使用的功能。


0
投票

使用ostream::write

ostream::write
© www.soinside.com 2019 - 2024. All rights reserved.