简体   繁体   English

用fstream方法读取二进制数据

[英]Reading binary data with fstream method

I need to read binary data to buffer, but in the fstreams I have read function reading data into char buffer, so my question is: 我需要将二进制数据读取到缓冲区,但是在fstream中,我已经读取了将数据读取到char缓冲区的函数,所以我的问题是:

How to transport/cast binary data into unsigned char buffer and is it best solution in this case? 如何将二进制数据传输/广播到无符号char缓冲区中?在这种情况下,这是最佳解决方案吗?

Example

  char data[54];
  unsigned char uData[54];
  fstream file(someFilename,ios::in | ios::binary);
  file.read(data,54);
  // There to transport **char** data into **unsigned char** data (?)
  // How to?

Just read it into unsigned char data in the first place 首先将其读入未签名的char数据中

unsigned char uData[54];
fstream file(someFilename,ios::in | ios::binary);
file.read((char*)uData, 54);

The cast is necessary but harmless. 演员表是必要的,但无害。

You don't need to declare the extra array uData. 您无需声明额外的数组uData。 The data array can simply be cast to unsigned: 数据数组可以简单地转换为无符号:

unsigned char* uData = reinterpret_cast<unsigned char*>(data);

When accessing uData you instruct the compiler to interpret the data different, for example data[3] == -1, means uData[3] == 255 访问uData时,您指示编译器解释不同的数据,例如data [3] == -1,表示uData [3] == 255

You could just use 你可以用

std::copy(data, data + n, uData);

where n is the result returned from file.read(data, 54) . 其中n是从file.read(data, 54)返回的结果。 I think , specifically for char* and unsigned char* you can also portably use 认为 ,特别是对于char*unsigned char*您也可以方便地使用

std::streamsize n = file.read(reinterpret_cast<char*>(uData));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM