Read stdin if no argument supplied

This commit is contained in:
Night Kaly 2024-11-06 14:52:20 +00:00
parent c0877d1a51
commit 652f3fc6a4
Signed by: night0721
SSH key fingerprint: SHA256:B/hgVwUoBpx5vdNsXl9w8XwZljA9766uk6T4ubZp5HM

33
nsh.c
View file

@ -210,25 +210,26 @@ void highlight_include(const char *line, int *i)
} }
} }
/* Main function to process input */ void highlight(char *filename)
int main(int argc, char **argv)
{ {
if (argc < 2) { char *ext;
fprintf(stderr, "nsh <file> <file2> ...\n"); FILE *f;
exit(1); if (filename == NULL) {
} f = stdin;
for (int i = 1; i < argc; i++) { } else {
FILE *f = fopen(argv[i], "r"); f = fopen(filename, "r");
if (!f) { if (!f) {
fprintf(stderr, "Unable to open file: %s\n", argv[i]); fprintf(stderr, "Unable to open file: %s\n", filename);
exit(1); exit(1);
} }
/* Handle file without extension */ /* Handle file without extension */
char *ext = strrchr(argv[i], '.'); ext = strrchr(filename, '.');
if (ext != NULL) { if (ext != NULL) {
/* How to identify file type if there isn't extension? */ /* How to identify file type if there isn't extension? */
ext++; ext++;
} }
}
char buffer[1024]; char buffer[1024];
char word[256]; char word[256];
int word_len = 0; int word_len = 0;
@ -336,6 +337,18 @@ int main(int argc, char **argv)
} }
} }
} }
}
/* Main function to process input */
int main(int argc, char **argv)
{
if (argc > 1) {
for (int i = 1; i < argc; i++) {
highlight(argv[i]);
}
} else {
highlight(NULL);
} }
return 0; return 0;
} }