#define _POSIX_C_SOURCE 200809L #include #include #include int main(int argc, char *argv[]) { FILE * cur_in_file; int i; char c; int using_unbuffered_output = 0; int error_occurred = 0; /* Check for -u and use unbuffered output if present */ while((c = getopt(argc, argv, "u")) != -1) { if(c == 'u') { using_unbuffered_output = 1; } } /* Set unbuffered output. We do this for both stdin and stdout, let setvbuf allocate the buffer (that we don't need), _IONBF tells it to not buffer, and we just say 15 character buffer because, well, eh, who cares? */ if(using_unbuffered_output) { setvbuf(stdin, NULL, _IONBF, 15); setvbuf(stdout, NULL, _IONBF, 15); } /* If no input files were given, just open up stdin */ if(argc == 1 || optind == argc) { cur_in_file = stdin; for(c = fgetc(cur_in_file); c != EOF; c = fgetc(cur_in_file)) { fprintf(stdout, "%c", c); } fclose(cur_in_file); } /* Open up each file given (or stdin if - was given), print it to stdout, then close it and move to the next while there are still files */ for(i = optind; i < argc; i++) { if(argv[i][0] == '-' && argv[i][1] == '\0') { cur_in_file = stdin; } else { cur_in_file = fopen(argv[i], "r"); if(cur_in_file == NULL) { fprintf(stderr, "%s: %s: No such file or directory\n", argv[0], argv[i]); error_occurred = 1; } } for(c = fgetc(cur_in_file); c != EOF; c = fgetc(cur_in_file)) { fprintf(stdout, "%c", c); } fclose(cur_in_file); } if(error_occurred) { return 1; } else { return 0; } }