(c ++)使用ifstream将.dat文件读取为十六进制

时间:2013-05-07 02:34:43

标签: c++ string binary hex ifstream

这是我的第一篇文章,如果我违反任何不成文的规则,我很抱歉。 :P我是初学者/中级程序员,我需要这个程序的帮助。

我试图将.dat文件中的.dat文件作为HEX输入/读/ ifstream(无论如何)变成一个大字符串。

我不想把它作为文字阅读。我想要十六进制格式,所以我可以搜索字符串并对其进行更改。 (像自动十六进制编辑器一样)

离。我的文件“00000000.dat”大小约为7kb。

在十六进制编辑器中,十六进制看起来像这样:

0A 00 00 0A 00 05 4C 65 76 65 6C 07 00 06 42 6C 6F 63 6B 73 00 00 80 00 07 FF 39
01 FF 03 03 02 FF 3F 00 07 FF 39 01 FF 03 03 02 FF 3F 00 07 FF 39 01 FF 03 03 02
FF 3F 00 07 FF 39 01 FF 03 03 02 FF 3F 00 07 FF 39 01 FF 03 03 02 FF 3F 00 07 FF
39 01 FF 03 03 02 FF 3F 00 07 FF 39 01 FF 03 03 02 FF 3F 00 07 FF 39 01 FF 03 03
02 FF 3F 00..... for a while...

我需要一个字符串变量(最好不要有空格)。

我当前的代码很糟糕,现在只打印结果。 (从ehow获得)并且似乎选择它想要输入/打印的内容。

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

using namespace std;

int main()
{
    ifstream input;
    input.open("00000000.dat");

    unsigned char h1,h2;

    do
    {
        input >> h1;
        cout << hex << (unsigned int)h1;
        input >> h2;
        cout << hex << (unsigned int)h2;
    }while(!input.eof());

cin.get();
return 0;
}

这是一个很大的文件,所以我无法显示你打印的内容,但它缺少一些字节。 (例如“0A 00 00 0A 00 05 .....”打印为“00 05 .....”)这也适用于结尾。

对不起,如果我没有解释清楚:(

2 个答案:

答案 0 :(得分:6)

如上所述,您应该将流打开为二进制文件。如果您告诉它不要跳过空格,您可以使用常规>>运算符。

unsigned char x;
std::ifstream input("00000000.dat", std::ios::binary);
input >> std::noskipws;
while (input >> x) {
    std::cout << std::hex << std::setw(2) << std::setfill('0')
              << (int)x;
}

要将内容转换为字符串,您可以使用ostringstream代替cout

答案 1 :(得分:0)

您想要将文件打开为二进制文件。你现在正在阅读文字。所以看起来应该是

//Open file object to read as binary
std::ifstream input("00000000.dat", std::ios::in | std::ios::binary);    

您也可能希望使用reinterpret_cast一次读取一个字节(即无法弄清楚您想要什么 - 您的代码和描述正在做相反的事情)。

//Read until end of file
while(!input.eof())    
{

    //Or .good() if you're paranoid about using eof()

    //Read file one byte at a time
    input.read(reinterpret_cast<char *>(&h1), sizeof(unsigned char));

}

或者,如果你只想要一个字符串中的所有内容,为什么不只是声明一个字符串并将其读入?