file io-如何在c++中读取二进制数据

file io - how can i read binary data in c++?

本文关键字:读取 二进制 数据 c++ io- file      更新时间:2023-10-16

我需要在C++中读写二进制数据。我使用from ofstreamifstream类,但它不能读取一些字符,如9,13,32。如果有其他方法可以读写主题。

使用std::ios::binary标志打开文件,然后使用.read(buffer,length);.write(buffer,length);,而不是流式操作符。

这里有一些例子:

https://cplusplus.com/reference/istream/istream/read/

https://cplusplus.com/reference/ostream/ostream/write/

这里有一个程序可以做到这一点:

#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 'x9xdx20x9xdx20n' >binfile
$ ./readbin binfile 
Read a 9
Read a 13
Read a 32
Read a 9
Read a 13
Read a 32
Read a 10

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

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