From 2269ec267c89c862d6c5200df21c33d138273303 Mon Sep 17 00:00:00 2001 From: apio Date: Fri, 28 Oct 2022 17:14:20 +0200 Subject: [PATCH] apps: Add a 'stat' utility --- apps/Makefile | 2 +- apps/src/stat.c | 55 +++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 56 insertions(+), 1 deletion(-) create mode 100644 apps/src/stat.c diff --git a/apps/Makefile b/apps/Makefile index a6456fd8..709f0cd2 100644 --- a/apps/Makefile +++ b/apps/Makefile @@ -1,4 +1,4 @@ -APPS := init sym sh crash uname uptime hello ps ls args cat +APPS := init sym sh crash uname uptime hello ps ls args cat stat APPS_DIR := $(LUNA_ROOT)/apps APPS_SRC := $(APPS_DIR)/src diff --git a/apps/src/stat.c b/apps/src/stat.c new file mode 100644 index 00000000..d07035d1 --- /dev/null +++ b/apps/src/stat.c @@ -0,0 +1,55 @@ +#include +#include +#include + +const char* mode_to_string(mode_t mode) +{ + static char mode_string[12]; + + char mode_set[12] = {'s', 'g', 'r', 'w', 'x', 'r', 'w', 'x', 'r', 'w', 'x', 0}; + mode_t mode_val[12] = {S_ISUID, S_ISGID, S_IRUSR, S_IWUSR, S_IXUSR, S_IRGRP, + S_IWGRP, S_IXGRP, S_IROTH, S_IWOTH, S_IXOTH, S_IFMT}; + + for (int i = 0; i < 12; i++) + { + if (mode & mode_val[i]) mode_string[i] = mode_set[i]; + else + mode_string[i] = '-'; + } + + return mode_string; +} + +int main(int argc, char** argv) +{ + if (argc == 1) + { + fprintf(stderr, "Usage: stat [file]\n"); + return EXIT_FAILURE; + } + + struct stat st; + if (stat(argv[1], &st) < 0) + { + perror("stat"); + return EXIT_FAILURE; + } + + printf("Type: "); + + switch (st.st_mode & S_IFMT) + { + case S_IFREG: puts("Regular file"); break; + case S_IFDIR: puts("Directory"); break; + case S_IFCHR: puts("Character device"); break; + default: puts("Unknown"); break; + } + + printf("Length: %ld\n", st.st_size); + printf("Inode: %ld\n", st.st_ino); + printf("UID: %d\n", st.st_uid); + printf("GID: %d\n", st.st_gid); + printf("Mode: %s\n", mode_to_string(st.st_mode)); + + return EXIT_SUCCESS; +} \ No newline at end of file