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

cat.c

Name: Anonymous 2012-02-16 3:42

ITT: make your best, most elegant implementation of cat(1) in C. Doesn't have to be POSIX compliant; for example, mine takes no option arguments because that's how I think it should be, whereas I think that POSIX specifies a few options.

#include <stdio.h>
int main(int argc, char **argv) {
    char b[4096];
    FILE *f = stdin;
    int i;
    size_t s;
    if (argc == 1)
        goto noargs;
    for (i = 1; i < argc; i++) {
        f = fopen(argv[i], "rb");
        if (!f) {
            fprintf(stderr, "%s: failed to open %s\n", argv[0], argv[i]);
            continue;
        }
        noargs:
        while ((s = fread(b, 1, 4096, f)))
            fwrite(b, 1, s, stdout);
    }
    return 0;
}


Why is this the best in my opinion? It is short, simple, fast, serves just the purpose of concatenating files and no more, and even has a clever and elegant trick to handle the special case of no arguments without code duplication.

Name: Anonymous 2012-02-16 4:05

>>5
I can't do it using standard C, but:

        while ((s = fread(b, 1, 4096, f)))
            fwrite(b, 1, s, stdout);


could be wrapped in a function, and then this function can be called from within the loop, and instead of using a goto to jump into the middle of the loop, you can just call the function.

Or is that correct? When you jump into the middle of the loop there, you expect the loop to terminate right? IE, the catting code is only run once? I don't think i is necessarily initialized when the comparison, i < argc is made.

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