Search code examples
c++hexdump

Extract hexdump or RAW data of a file to text


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


Solution

  • 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;
    }