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

时间:2011-06-13 11:32:48

标签: c++ file-io

我需要用C ++读取和写入二进制数据。我使用的是ofstreamifstream类,但它不能读取像9,13,32这样的字符。如果有另一种方法可以读写主题。

3 个答案:

答案 0 :(得分:6)

使用std::ios::binary标志打开文件,然后使用readwrite而非流媒体运营商。

这里有一些例子:

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

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

答案 1 :(得分:2)

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

#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;
}

以下是在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

答案 2 :(得分:1)

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

// 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( );