Luna/apps/cat.cpp

46 lines
851 B
C++
Raw Normal View History

2023-03-29 20:10:51 +00:00
#include <os/ArgumentParser.h>
2023-03-23 23:52:26 +00:00
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
2023-03-29 20:10:51 +00:00
static void do_cat(StringView path)
2023-03-23 23:52:26 +00:00
{
2023-03-29 20:10:51 +00:00
FILE* f;
if (path == "-") f = stdin;
else
{
f = fopen(path.chars(), "r");
if (!f)
{
perror(path.chars());
exit(1);
}
}
2023-03-23 23:52:26 +00:00
char buffer[4096];
while (1)
{
size_t nread = fread(buffer, 1, sizeof(buffer), f);
if (nread == 0) return;
fwrite(buffer, 1, nread, stdout);
}
2023-03-29 20:10:51 +00:00
if (f != stdin) fclose(f);
2023-03-23 23:52:26 +00:00
}
int main(int argc, char** argv)
{
2023-03-29 20:10:51 +00:00
StringView filename;
2023-03-23 23:52:26 +00:00
os::ArgumentParser parser;
2023-03-29 20:10:51 +00:00
parser.add_positional_argument(filename, "file"_sv, "-"_sv);
Vector<StringView> extra_files = parser.parse(argc, argv).value();
do_cat(filename);
for (auto file : extra_files) { do_cat(file); }
2023-03-23 23:52:26 +00:00
}