cat: Use ArgumentParser
All checks were successful
continuous-integration/drone/push Build is passing

This commit is contained in:
apio 2023-03-29 22:10:51 +02:00
parent e6645ed607
commit 43f90c4f88
Signed by: apio
GPG Key ID: B8A7D06E42258954
2 changed files with 28 additions and 22 deletions

View File

@ -7,9 +7,11 @@ function(luna_app SOURCE_FILE APP_NAME)
endfunction() endfunction()
luna_app(init.cpp init) luna_app(init.cpp init)
luna_app(cat.cpp cat)
luna_app(sh.cpp sh) luna_app(sh.cpp sh)
luna_app(cat.cpp cat)
target_link_libraries(cat PRIVATE os)
luna_app(date.cpp date) luna_app(date.cpp date)
target_link_libraries(date PRIVATE os) target_link_libraries(date PRIVATE os)

View File

@ -1,9 +1,24 @@
#include <os/ArgumentParser.h>
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <string.h> #include <string.h>
static void do_cat(FILE* f) static void do_cat(StringView path)
{ {
FILE* f;
if (path == "-") f = stdin;
else
{
f = fopen(path.chars(), "r");
if (!f)
{
perror(path.chars());
exit(1);
}
}
char buffer[4096]; char buffer[4096];
while (1) while (1)
@ -12,30 +27,19 @@ static void do_cat(FILE* f)
if (nread == 0) return; if (nread == 0) return;
fwrite(buffer, 1, nread, stdout); fwrite(buffer, 1, nread, stdout);
} }
if (f != stdin) fclose(f);
} }
int main(int argc, char** argv) int main(int argc, char** argv)
{ {
FILE* f; StringView filename;
if (argc < 2) { do_cat(stdin); } ArgumentParser parser;
else parser.add_positional_argument(filename, "file"_sv, "-"_sv);
{ Vector<StringView> extra_files = parser.parse(argc, argv).value();
for (int i = 1; i < argc; i++)
{
if (!strcmp(argv[i], "-")) f = stdin;
else
{
f = fopen(argv[i], "r");
if (!f)
{
perror(argv[i]);
return 1;
}
}
do_cat(f); do_cat(filename);
if (f != stdin) fclose(f);
} for (auto file : extra_files) { do_cat(file); }
}
} }