【问题标题】:how to read binary file content as strings?如何将二进制文件内容读取为字符串?
【发布时间】:2025-12-17 19:20:04
【问题描述】:

我需要从二进制文件中读取 16 位为std::stringchar *。例如,一个二进制文件包含89 ab cd ef,我希望能够将它们提取为std::strings 或char *。我试过以下代码:

ifstream *p = new ifstream();
char *buffer;  
p->seekg(address, ios::beg);  
buffer = new char[16];  
memset(buffer, 0, 16);  
p->read(buffer, 16);  

当我尝试std::cout 缓冲区时,什么也没出现。如何读取二进制文件中的这些字符?

编辑:我正在寻找一个 int 类型的缓冲区,例如“0x89abcdef”。有没有可能实现?

【问题讨论】:

  • 这段代码执行时address的值是多少?
  • 你打开文件了吗?此外,在堆栈上声明 *p 可能是一个更好的主意:ifstream p("somefile.txt");
  • 您希望在缓冲区中获得什么?您是否希望它包含四个字节,其值分别为 0x89、0xAB、0xCD、0xEF?或者您是否尝试获取这些值的一些文本表示形式(例如,"89 ab cd ef" 之类的字符串)?
  • 如果您在 Linux 中,您可以使用 strings bin_file_path 从二进制文件中获取所有字符串的列表
  • 当您尝试从文件中读取数据时,您应该始终检查尝试是否成功。例如,当ifstream::read 未能读取您要求的尽可能多的字节时,它会在流对象上设置一些标志,您可以使用ifstream::failifstream::eof 进行检查。

标签: c++ filestream binaryfiles


【解决方案1】:

类似:

#include <string>
#include <iostream>
#include <fstream>
#include <iomanip>

int main()
{
    if (ifstream input("filename"))
    {
        std::string s(2 /*bytes*/, '\0' /*initial content - irrelevant*/);
        if (input.read(&s[0], 2 /*bytes*/))
            std::cout << "SUCCESS: [0] " << std::hex << (int)s[0] << " [1] " << (int)s[1] << '\n';
        else
            std::cerr << "Couldn't read from file\n";
    }
    else
        std::cerr << "Couldn't open file\n";
}

【讨论】:

    【解决方案2】:

    您不能像读取文本一样读取二进制流。

    当然,您可以读取二进制文件(通过在流对象上使用“file.read()”和“file.write()”方法)。就像你现在所做的一样:)

    您还可以将二进制转换为文本:“转换为十六进制文本字符串”和“uuencode base 64”是执行此操作的两种常用方法。

    【讨论】:

      【解决方案3】:

      您需要将字节读取为数字(可能是 long long 类型)。 然后您可以使用格式说明符like this 打印那些:

      #include <iostream>
      #include <iomanip>
      
      int main()
      {
          using namespace std;
      
          int x =   2;
          int y = 255;
      
          cout << showbase // show the 0x prefix
               << internal // fill between the prefix and the number
               << setfill('0'); // fill with 0s
      
          cout << hex << setw(4) << x << dec << " = " << setw(3) << x << endl;
          cout << hex << setw(4) << y << dec << " = " << setw(3) << y << endl;
      
          return 0;
      }
      

      【讨论】:

        最近更新 更多