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.
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.
#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.