Rewrote cat utility
This commit is contained in:
parent
8ee74d84e3
commit
7163fbe175
|
@ -1,2 +1,3 @@
|
||||||
*~
|
*~
|
||||||
build
|
build
|
||||||
|
vgcore*
|
||||||
|
|
56
src/cat.c
56
src/cat.c
|
@ -1,18 +1,50 @@
|
||||||
#include <stdio.h>
|
#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[]){
|
int main(int argc, char *argv[]){
|
||||||
char ch;
|
char ch;
|
||||||
for (int i = 1; i < argc; i++) {
|
int opt;
|
||||||
FILE *file = fopen(argv[i], "r");
|
FILE *file = stdin;
|
||||||
if (file == NULL ) {
|
while ((opt = getopt(argc, argv, ":u")) != -1) {
|
||||||
printf("Cannot find file: %s\n", argv[1]);
|
switch (opt) {
|
||||||
return 1;
|
case 'u':
|
||||||
}
|
break;
|
||||||
|
case '?':
|
||||||
|
fprintf(stderr, "%s: invalid option -- '%c'\n", argv[0], optopt);
|
||||||
|
return usage(argv[0]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
while ((ch = fgetc(file)) != EOF)
|
if (optind == argc) { // FIXME: this code is not clean
|
||||||
{
|
goto READ_STDIN;
|
||||||
putchar(ch);
|
}
|
||||||
}
|
|
||||||
fclose(file);
|
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;
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in New Issue