(C ++)读取.dat文件与使用十六进制的ifstream [英] (c++) Read .dat file as hex using ifstream

查看:4246
本文介绍了(C ++)读取.dat文件与使用十六进制的ifstream的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

This is my first post so sorry if I break any unwritten rules. :P I am a beginner/intermediate programmer and I need help with this program.

我想INFILE /读/ ifstream的(任何).dat文件为HEX成一个大的字符串。

I am trying to infile/read/ifstream (whatever) a .dat file as HEX into one big string.

我不想读它为文本。我想要的十六进制格式,所以我可以通过搜索字符串,并进行更改。 (像自动十六进制编辑器)

I don't want to read it as text. I want the hex format so I can search through the string and make changes to it. (Like an automatic hex editor)

恩。我的文件00000000.dat是〜7KB大小。

ex. my file "00000000.dat" is ~7kb in size.

在十六进制编辑器,六角是这样的:

In hex editor, the hex look like this:

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...

我需要这一切在一个字符串变量(不带空格pferably $ P $)。

I need all of it in a string variable (with no spaces preferably).

我目前的code吸,现在只打印结果。 (从ehow了它),似乎挑选它想要什么输入/打印。

My current code sucks and for now only prints the result. (got it from ehow) and seems to pick and choose what it wants to input/print.

#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 00 0A 05 .....打印为00 05 .....),这是为结束以及真实的。

It's a big file so I can't show yo what it prints, but it is missing some bytes. (ex "0A 00 00 0A 00 05....." prints as "00 05.....") this is true for the ending as well.

很抱歉,如果我没有解释得很好:(

Sorry if I didn't explain it well :(

推荐答案

您应该打开流为二进制,如前所述。您可以使用普通的&GT;方式&gt; 运营商,如果你告诉它不要跳过空格

You should open the stream as binary, as mentioned. You can use the regular >> operator if you tell it not to skip white space.

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

To get the content into a string, you can use an ostringstream instead of cout.

这篇关于(C ++)读取.dat文件与使用十六进制的ifstream的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆