apps: Add cat

This commit is contained in:
apio 2022-10-26 20:51:20 +02:00
parent 2512acc716
commit d5a64319f9
2 changed files with 63 additions and 1 deletions

View File

@ -1,4 +1,4 @@
APPS := init sym sh crash uname uptime hello ps ls args APPS := init sym sh crash uname uptime hello ps ls args cat
APPS_DIR := $(LUNA_ROOT)/apps APPS_DIR := $(LUNA_ROOT)/apps
APPS_SRC := $(APPS_DIR)/src APPS_SRC := $(APPS_DIR)/src

62
apps/src/cat.c Normal file
View File

@ -0,0 +1,62 @@
#define _GNU_SOURCE // for program_invocation_name
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
void cat(FILE* stream)
{
struct stat statbuf;
fstat(fileno(stream), &statbuf);
if (statbuf.st_mode == __VFS_DEVICE) // FIXME: Add S_ISDEV.
{
char buf[4096]; // FIXME: Do not limit ourselves to 4096 bytes. Devices which can't seek and are constant should
// return EOF after the first read.
fgets(buf, 4096, stream);
if (ferror(stream))
{
perror(program_invocation_name);
exit(EXIT_FAILURE);
}
if (feof(stream)) return;
fputs(buf, stdout);
return;
}
char buf[BUFSIZ];
do {
fgets(buf, BUFSIZ, stream);
if (ferror(stream))
{
perror(program_invocation_name);
exit(EXIT_FAILURE);
}
fputs(buf, stdout);
} while (!feof(stream));
}
int main(int argc, char** argv)
{
if (argc == 1) cat(stdin);
else
{
for (int i = 1; i < argc; i++)
{
if (strcmp(argv[i], "-") == 0) cat(stdin);
else if (strcmp(argv[i], "-n") == 0 || strcmp(argv[i], "--newline") == 0)
putchar('\n');
else
{
FILE* stream = fopen(argv[i], "r");
if (!stream)
{
perror(program_invocation_name);
return EXIT_FAILURE;
}
cat(stream);
fclose(stream);
}
}
}
}