Skip to content

Hexdump

hexdump

#include <stdlib.h>
#include <stdio.h>
#include <string>
#include <fcntl.h>
#include <unistd.h>
#include <stdint.h>
#include <sys/stat.h>
#include <sys/mman.h>

using std::string;
int main(int argc, char** argv)
{
    string file = "";

    for(int i =1; i<argc; i++)
    {
        string opt = argv[i];
        printf("using option %s \n", opt.c_str());
        if( opt == "-f")
        {
            file = argv[++i];
            printf(" -f  %s \n", file.c_str());
        }
        else
        {
            printf("error, invalid option %s \n", opt.c_str());
            return -1;
        }
    }

    int fd = open(file.c_str(), O_RDONLY);
    if (fd == -1)
    {
        printf("error, cant open file %s \n", file.c_str());
        return -1;
    }
    struct stat fileStat;
    fstat(fd, &fileStat);
    if (fileStat.st_size == 0)
    {
        printf("file is empty, exiting \n");
    }

    uint8_t *data = static_cast<uint8_t*>(mmap(NULL, fileStat.st_size, PROT_READ, MAP_SHARED, fd, 0));
    for (uint64_t index = 0; index < static_cast<uint64_t>(fileStat.st_size);)
    {
        printf(" %08lx  :  ", index);
        for (int i = 0; i <16; i++)
        {
            if (i == 7)
                printf("  ");
            printf("%2x ", data[index+i]);
        }
        printf(" | ");
        for (int i = 0; i <16; i++)
        {
            if (i == 7)
                printf("  ");
            printf("%c ", static_cast<char>(data[index+i]));
        }
        index += 16;
        printf(" \n");
    }

    int ret = munmap( data, fileStat.st_size);
    if (ret != 0 )
    {
        printf("error, unmap fail \n");
        return -1;
    }

    ret = close(fd);
    if (ret != 0)
    {
        printf("error, cant close file %s \n", file.c_str());
        return -1;
    }

    return 0;
}