簡體   English   中英

在C ++中將文件讀取為十六進制

[英]Reading file as hex in C++

我目前正在編寫一個帶有客戶端 - 服務器架構(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;
    }
}

我得到了

二進制表達式的操作數無效('std :: string'(又名'basic_string,allocator>')和'std :: __ 1 :: ios_base&(std :: __ 1 :: ios_base&)')

現在錯誤,我想出了編譯器抱怨的那個,因為它不想逐字節讀入std :: string。 但是,為什么我不知道。

如果你能幫我找到更好的方法,我會很高興的。 我喜歡有關如何將文件拆分為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] );
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM