Extract hexdump or RAW data of a file to text

2019-05-10 23:31发布

问题:

I was wondering if there is a way to output the hexdump or raw data of a file to txt file. for example I have a file let's say "data.jpg" (the file type is irrelevant) how can I export the HEXdump (14ed 5602 etc) to a file "output.txt"? also how I can I specify the format of the output for example, Unicode or UTF? in C++

回答1:

This is pretty old -- if you want Unicode, you'll have to add that yourself.

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char **argv) {
    unsigned long offset = 0;
    FILE *input;
    int bytes, i, j;
    unsigned char buffer[16];
    char outbuffer[60];

    if ( argc < 2 ) {
        fprintf(stderr, "\nUsage: dump filename [filename...]");
        return EXIT_FAILURE;
    }

    for (j=1;j<argc; ++j) {

        if ( NULL ==(input=fopen(argv[j], "rb")))
            continue;

        printf("\n%s:\n", argv[j]);

        while (0 < (bytes=fread(buffer, 1, 16, input))) {
            sprintf(outbuffer, "%8.8lx: ", offset+=16);
            for (i=0;i<bytes;i++) {
                sprintf(outbuffer+10+3*i, "%2.2X ",buffer[i]);
                if (!isprint(buffer[i]))
                    buffer[i] = '.';
            }
            printf("%-60s %*.*s\n", outbuffer, bytes, bytes, buffer);
        }
        fclose(input);
    }
    return 0;
}


回答2:

You can use a loop, fread and fprintf: With read you get the byte-value of the bytes, then with fprintf you can use the %x to print hexadecimal to a file.

http://www.cplusplus.com/reference/clibrary/cstdio/fread/

http://www.cplusplus.com/reference/clibrary/cstdio/fprintf/

If you want this to be fast you load whole machine-words (int or long long) instead of single bytes, if you want this to be even faster you fread a whole array, then sprintf a whole array, then fprintf that array to the file.



回答3:

Maybe something like this?

#include <sstream>
#include <iostream>
#include <iomanip>
#include <iterator>
#include <algorithm>

int main()
{
    std::stringstream buffer( "testxzy" );
    std::istreambuf_iterator<char> it( buffer.rdbuf( ) );
    std::istreambuf_iterator<char> end; // eof

    std::cout << std::hex << std::showbase;

    std::copy(it, end, std::ostream_iterator<int>(std::cout));

    std::cout << std::endl;

    return 0;
}

You just have to replace buffer with an ifstream that reads the binary file, and write the output to a textfile using an ofstream instead of cout.



标签: c++ hexdump