我如何在 C++ 中读取二进制数据?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6329857/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 19:56:46  来源:igfitidea点击:

how can i read binary data in c++?

c++file-io

提问by Mahdi_Nine

I need to read and write binary data in C++.I use from ofstreamand ifstreamclasses but it can't read some chars like 9,13,32.If is there another way to read and write theme.

我需要在 C++ 中读取和写入二进制数据。我使用 fromofstreamifstreamclasses 但它无法读取一些字符,如 9、13、32。如果有另一种方式来读取和写入主题。

采纳答案by Omnifarious

Here is a program that does this:

这是一个执行此操作的程序:

#include <iostream>
#include <fstream>

int main(int argc, const char *argv[])
{
   if (argc < 2) {
      ::std::cerr << "Usage: " << argv[0] << "<filename>\n";
      return 1;
   }
   ::std::ifstream in(argv[1], ::std::ios::binary);
   while (in) {
      char c;
      in.get(c);
      if (in) {
         ::std::cout << "Read a " << int(c) << "\n";
      }
   }
   return 0;
}

Here is an example of it being run in Linux:

这是它在 Linux 中运行的示例:

$ echo -ne '\x9\xd\x20\x9\xd\x20\n' >binfile
$ ./readbin binfile 
Read a 9
Read a 13
Read a 32
Read a 9
Read a 13
Read a 32
Read a 10

回答by Stuart Golodetz

Open the file using the std::ios::binaryflag and then use readand writerather than the streaming operators.

使用std::ios::binary标志打开文件,然后使用readandwrite而不是流操作符。

There are some examples here:

这里有一些例子:

http://www.cplusplus.com/reference/iostream/istream/read/

http://www.cplusplus.com/reference/iostream/istream/read/

http://www.cplusplus.com/reference/iostream/ostream/write/

http://www.cplusplus.com/reference/iostream/ostream/write/

回答by gmas80

This is a basic example (without any error check!):

这是一个基本示例(没有任何错误检查!):

// Required STL
#include <fstream>
using namespace std;

// Just a class example
class Data
{
   int    a;
   double b;
};

// Create some variables as examples
Data x;
Data *y = new Data[10];

// Open the file in input/output
fstream myFile( "data.bin", ios::in | ios::out | ios::binary );

// Write at the beginning of the binary file
myFile.seekp(0);
myFile.write( (char*)&x, sizeof (Data) );

...

// Assume that we want read 10 Data since the beginning
// of the binary file:
myFile.seekg( 0 );
myFile.read( (char*)y, sizeof (Data) * 10 );

// Remember to close the file
myFile.close( );