HTMLify
cat
Views: 156 | Author: abh
/* 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;
}