FENIX_coreutils/cat.c

73 lines
1.7 KiB
C
Raw Normal View History

#define _POSIX_C_SOURCE 200809L
#include <stdio.h>
#include <stdlib.h>
2020-12-02 02:32:26 +00:00
#include <unistd.h>
int main(int argc, char *argv[]) {
2020-12-13 15:25:50 +00:00
FILE * cur_in_file;
2020-12-02 02:32:26 +00:00
int i; char c;
int using_unbuffered_output = 0;
2020-12-02 02:32:26 +00:00
int error_occurred = 0;
2020-12-02 02:32:26 +00:00
2022-10-06 07:12:56 +00:00
/*
Check for -u and use unbuffered output if present
*/
2020-12-13 15:25:50 +00:00
while((c = getopt(argc, argv, "u")) != -1) {
if(c == 'u') {
using_unbuffered_output = 1;
}
}
2022-10-06 07:12:56 +00:00
/*
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?
*/
2022-02-28 03:38:10 +00:00
if(using_unbuffered_output) {
setvbuf(stdin, NULL, _IONBF, 15);
setvbuf(stdout, NULL, _IONBF, 15);
}
2022-10-06 07:12:56 +00:00
/*
If no input files were given, just open up stdin
*/
2020-12-13 15:25:50 +00:00
if(argc == 1 || optind == argc) {
cur_in_file = stdin;
for(c = fgetc(cur_in_file); c != EOF; c = fgetc(cur_in_file)) {
2022-02-28 03:38:10 +00:00
fprintf(stdout, "%c", c);
2020-12-02 02:32:26 +00:00
}
2020-12-13 15:25:50 +00:00
fclose(cur_in_file);
2020-12-02 02:32:26 +00:00
}
2022-10-06 07:12:56 +00:00
/*
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
*/
2020-12-13 15:25:50 +00:00
for(i = optind; i < argc; i++) {
2020-12-02 02:32:26 +00:00
if(argv[i][0] == '-' && argv[i][1] == '\0') {
2020-12-13 15:25:50 +00:00
cur_in_file = stdin;
2020-12-02 02:32:26 +00:00
}
else {
2020-12-13 15:25:50 +00:00
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;
}
}
2020-12-13 15:25:50 +00:00
for(c = fgetc(cur_in_file); c != EOF; c = fgetc(cur_in_file)) {
2022-02-28 03:38:10 +00:00
fprintf(stdout, "%c", c);
2020-12-02 02:32:26 +00:00
}
2020-12-13 15:25:50 +00:00
fclose(cur_in_file);
}
2020-12-02 02:32:26 +00:00
if(error_occurred) {
return 1;
2020-12-02 02:32:26 +00:00
}
else {
return 0;
2020-12-02 02:32:26 +00:00
}
}