News Uni Dev Res Blag

cat | hexdump -C

2010/11/05 - 05:02

hexdump.cpp

#include <cstdio>
#include <fstream>
using namespace std;

/* Dear Diary
 * Today I reinvented the wheel
 * 
 * love, ed
 */

int main(int argc, char **argv)
{
    // Default values
    string path = "";
    string pipe = "";
    string arg = "-text";
    bool text = false;

    // Parse arguments
    for (int a = 1; a < argc; a++)
    {
        if (arg.compare(argv[a]) == 0)
        {
            text = true;
        }
        else
        {
            if (path.length() < 1) {
                path = argv[a];
            }
            else if (pipe.length() < 1)
            {
                pipe = argv[a];
            }
        }
    }

    FILE* o;
    if (pipe.length() < 1) {
        o = stdout;
    }
    else
    {
        o = fopen(pipe.c_str(), "w");
    }

    char *cache;
    long ofs = 0;
    const int SZ = 0x10;
    cache = new char[SZ];
    ifstream input(path.c_str(), ios::in | ios::binary);

    while (input && input.is_open())
    {
        fprintf(o, "%6lx  ", ofs);
        ofs += SZ;

        int read = SZ;
        if (!input.read(cache, SZ))
        {
            read = input.gcount();
        }

        for (int a = 0; a < read; a++)
        {
            fprintf(o, "%.2x ", cache[a]);
        }

        if (text)
        {
            int w = 3 * (SZ-read);
            if (w > 0)
            {
                w++;
            }
            fprintf(o, "%*c", w, ' ');
            fprintf(o, "%.*s", read, cache);
        }
        fprintf(o, "\n");
    }
    if (!pipe.length() < 1)
    {
        fclose(o);
    }
}

Copyright © 2010 Ed Edland