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-06 5:46 ID:QsPw0j9L

Hint 1: char is signed by default, which is a design flaw of C.
Hint 2: Stop treating characters as bytes you fucking noob! Use wchar_t whenever possible. All character sets are legacy (even ASCII - American Shit Code for Idiots and Imbeciles), the only character set that's not legacy is ISO 10646 and the only character encodings that are not legacy are the Unicode Transformation Formats (UTF).

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