繁体   English   中英

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

[英](c++) Read .dat file as hex using ifstream

这是我的第一篇文章,非常抱歉,如果我违反任何未成文的规定。 :PI是初学者/中级程序员,我需要有关此程序的帮助。

我正在尝试将.dat文件(不管是什么)作为十六进制文件infile / read / 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...

我需要所有这些都在一个字符串变量中(最好没有空格)。

我当前的代码很烂,现在只显示结果。 (通过电子方式获得),似乎可以选择并选择要输入/打印的内容。

#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 .....”)对于结尾也是如此。

对不起,如果我没有很好地解释:(

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

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

您想打开文件以二进制形式读取。 您正在以文本形式阅读。 所以应该看起来像

//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));

}

或者,如果您只想将所有内容都放在一个字符串中,为什么不只声明一个字符串并将其读入该字符串中呢?

暂无
暂无

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

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