在C++中以十六进制读取文件

Reading file as hex in C++

本文关键字:读取 文件 十六进制 C++      更新时间:2023-10-16

我目前正在编写一个具有客户端-服务器架构(TCP通信)的iOS应用程序。我现在正在服务器端编写一个模块,该模块应该以十六进制值读取声音文件,并将声音文件1024乘1024字节发送到客户端。

我不是一个经验丰富的C++开发人员,我需要一些帮助来阅读文件。现在我的代码是:

void PacketInterpreter::sendFile(int turn, int gameID){
    std::string absoluteFilePath = (std::to_string(gameID) + "/sound.caf");
    unsigned char x;
    std::ifstream file(absoluteFilePath, std::ios::binary);
    file >> std::noskipws;
    std::string outstream;
    while(file >> x){
        outstream << std::hex << (int)x;
    }
}

我正在获取

二进制表达式("st::string"(又名'basic_string,allocater>')和'std::__1::ios_base&(std::__1::ios_base&)')

现在出现错误,我想这是编译器抱怨的原因,因为它不想逐字节读取std::字符串。然而,我不知道为什么。

如果你能帮我找到更好的方法,我会很高兴的。我也很想了解如何将文件拆分为1024字节的块。提前感谢!

不要对二进制文件使用格式化的流插入(<<)或提取(>>)运算符。

相反,请使用istream::readostream::write方法。

编辑1:块读取示例

#define BUFFER_CAPACITY 512
unsigned char buffer[BUFFER_CAPACITY];
ifstream input_data("my_data.caf");
input_data.read((unsigned char)&buffer[0], sizeof(buffer));
//...
cout << "Look, first by is "
     << "0x" << hex << buffer[0]
     << " or as decimal: " << dec << buffer[0]
     << endl;

由于OP还要求读取1K块,并希望警告不会产生成对十六进制数字的简单十六进制,因此这里有一个更全面的解决方案草案。错误处理是粗略的,但不应该被忽略。

#include <fstream>
#include <iostream>
#include <iomanip>
void process( char* buffer, size_t len ){
  for( int i = 0; i < len; i++ ){
    std::cout << std::setbase( 16 ) << std::setw( 2 ) << std::setfill( '0' )
              << (unsigned)buffer[i];
  }
}
void sendfile( char * pathname ){
  std::ifstream ifs( pathname, std::ifstream::in );
  if( ifs.fail() ) throw "error opening";
  const std::size_t BUFFER_SIZE = 1024;
  char buffer [BUFFER_SIZE];
  size_t nRead = 0;
  while( ifs.read (buffer, sizeof(buffer)) ){
    process( buffer, ifs.gcount() );
  }
  if( ! ifs.eof() ) throw "error reading";
  process( buffer, ifs.gcount() );
  ifs.close();
}
int main( int argc, char* args[] ){
  if( 0 == argc ) throw "missing argument";
  sendfile( args[1] );
}