Userspace: Add basic chmod command

This commit is contained in:
Bananymous 2023-10-25 02:36:09 +03:00
parent 15bb1804ef
commit 7a54a088b4
3 changed files with 61 additions and 0 deletions

View File

@ -5,6 +5,7 @@ project(userspace CXX)
set(USERSPACE_PROJECTS set(USERSPACE_PROJECTS
cat cat
cat-mmap cat-mmap
chmod
cp cp
dd dd
echo echo

View File

@ -0,0 +1,17 @@
cmake_minimum_required(VERSION 3.26)
project(chmod CXX)
set(SOURCES
main.cpp
)
add_executable(chmod ${SOURCES})
target_compile_options(chmod PUBLIC -O2 -g)
target_link_libraries(chmod PUBLIC libc)
add_custom_target(chmod-install
COMMAND sudo cp ${CMAKE_CURRENT_BINARY_DIR}/chmod ${BANAN_BIN}/
DEPENDS chmod
USES_TERMINAL
)

43
userspace/chmod/main.cpp Normal file
View File

@ -0,0 +1,43 @@
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
void usage(const char* argv0, int ret)
{
FILE* out = (ret == 0) ? stdout : stderr;
fprintf(out, "usage: %s MODE FILE...\n", argv0);
fprintf(out, " Change the mode of each FILE to MODE.\n");
exit(ret);
}
int main(int argc, char** argv)
{
if (argc <= 2)
usage(argv[0], 1);
int base = (argv[1][0] == '0') ? 8 : 10;
mode_t mode = 0;
for (const char* ptr = argv[1]; *ptr; ptr++)
{
if (!isdigit(*ptr))
{
fprintf(stderr, "Invalid MODE %s\n", argv[1]);
usage(argv[0], 1);
}
mode = (mode * base) + (*ptr - '0');
}
int ret = 0;
for (int i = 2; i < argc; i++)
{
if (chmod(argv[i], mode) == -1)
{
perror("chmod");
ret = 1;
}
}
return ret;
}