HTMLify
cat
Views: 177 | Author: abh
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 | /* cat */ #define POSIX_C_SOURCE 200809L #include <stdio.h> #include <string.h> #include <stdbool.h> #include <unistd.h> struct args { bool unbuffered; } args = { false }; void cat_file(FILE *file) { if (file == NULL) return; int byte; if (args.unbuffered) setvbuf(stdout, NULL, _IONBF, 0); while ((byte = getc(file)) != EOF) putchar(byte); } int main(int argc, char *argv[]) { int key; while ((key = getopt(argc, argv, "u")) != -1) { switch (key) { case 'u': { args.unbuffered = true; break; } default: { fprintf(stderr, "cat: invalid option -- '%c'", key); return 1; } } } argc -= optind; argv += optind; int return_code = 0; if (argc == 0) { cat_file(stdin); return 0; } for (int i=0; i<argc; i++) { if (!strcmp(argv[i], "-")) { cat_file(stdin); continue; } FILE *f = fopen(argv[i], "r"); if (!f) { fprintf(stderr, "cat: %s: No such file or directory\n", argv[i]); return_code = 1; continue; } cat_file(f); } return return_code; } |