Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

a hex dumper in C.. what do you think?

Name: Anonymous 2007-03-05 12:26 ID:k9b8HLy9

Here's the code tell me what you think

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

#define HEXFILE "hex.txt"
#define NONPRINTCHAR '.'
#define HEXNUM 8

int checksc(int c) {
    if(c == '\n' || c == '\r' || !isprint(c))
    return NONPRINTCHAR;
    return c;
}
int main(int argc, char **argv) {
   
    FILE *fp, *fp2;
    char buffer[HEXNUM + 2];
    int i = 0;
    int c;
    /* checking for arguments */
    if(argc == 1 || argc > 3) {
        fprintf(stderr, "%s -[option] file\n", argv[0]);
        return 1;
    }
    /* opening files and error checking */
    if(!(fp = fopen(argv[argc-1], "rb"))) {
            fprintf(stderr, "ERROR: unable to open %s for reading.\n", argv[1]);
            return 2;
    }
    if(!(fp2 = fopen(HEXFILE, "w"))) {
            fprintf(stderr, "ERROR: unable to open %s for writting.\n", HEXFILE);
            fclose(fp);
            return 3;
    }
    fprintf(fp2, "---- hex dump of %s ----\n\n", argv[argc-1]);
    memset(buffer, 0, HEXNUM + 2);
        while((c = fgetc(fp)) != EOF) {
            if(argc == 3) buffer[i] = (char)checksc(c);
            ++i;
            i%=HEXNUM;
            fprintf(fp2, "0x%x", c); // i would use %#x but it doens't work with 0.
            if(i) fputc(' ', fp2);
                else {
                    if(argc == 2) fputc('\n', fp2);
                    else if(argc == 3)
                            fprintf(fp2, "\t\t%s\n", buffer);
                    continue;
                    }
            if(c < 16) fputc(' ', fp2);
        }
    if(i) {
        buffer[i] = 0;
        fprintf(fp2, "\t\t%s\n", buffer);
    }
    fprintf(fp2, "\n\n---- EOF ----");
    fclose(fp);
    fclose(fp2);
    return 0;
}

Name: Anonymous 2007-03-05 13:01 ID:3EhMBYtC

Not bad, though I would've singled out 0 as a special case and used %0#x for all others.

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List