Rewrote cat utility

This commit is contained in:
g1n 2022-06-30 09:12:07 +03:00
parent 8ee74d84e3
commit 7163fbe175
Signed by: g1n
GPG Key ID: 8D352193D65D4E2C
2 changed files with 45 additions and 12 deletions

1
.gitignore vendored
View File

@ -1,2 +1,3 @@
*~
build
vgcore*

View File

@ -1,18 +1,50 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
int usage(char *argv0) {
printf("Usage: %s [-u] [file ...]\n", argv0);
return 2;
}
int main(int argc, char *argv[]){
char ch;
for (int i = 1; i < argc; i++) {
FILE *file = fopen(argv[i], "r");
if (file == NULL ) {
printf("Cannot find file: %s\n", argv[1]);
return 1;
}
int opt;
FILE *file = stdin;
while ((opt = getopt(argc, argv, ":u")) != -1) {
switch (opt) {
case 'u':
break;
case '?':
fprintf(stderr, "%s: invalid option -- '%c'\n", argv[0], optopt);
return usage(argv[0]);
}
}
while ((ch = fgetc(file)) != EOF)
{
putchar(ch);
}
fclose(file);
}
if (optind == argc) { // FIXME: this code is not clean
goto READ_STDIN;
}
for (; optind < argc; optind++) {
if (strcmp(argv[optind], "-")) {
file = fopen(argv[optind], "r");
if (file == NULL) {
fprintf(stderr, "%s: ", argv[0]);
perror(argv[optind]);
return -1;
}
} else {
file = stdin;
}
READ_STDIN:
while ((ch = fgetc(file)) != EOF) {
putchar(ch);
}
if (file != NULL && file != stdin) {
fclose(file);
}
}
return 0;
}