Skip to content

Commit

Permalink
dirname: implementation of the dirname command
Browse files Browse the repository at this point in the history
  • Loading branch information
jewelcodes committed Jan 27, 2025
1 parent d5cbe7f commit 26bd6e1
Show file tree
Hide file tree
Showing 3 changed files with 93 additions and 1 deletion.
8 changes: 7 additions & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ all:
@make -C rm
@echo "\x1B[0;1;35m make\x1B[0m utilities/ln"
@make -C ln
@echo "\x1B[0;1;35m make\x1B[0m utilities/dirname"
@make -C dirname

install:
@mkdir -p out
Expand Down Expand Up @@ -62,6 +64,8 @@ install:
@make install -C rm
@echo "\x1B[0;1;35m make\x1B[0m install utilities/ln"
@make install -C ln
@echo "\x1B[0;1;35m make\x1B[0m install utilities/dirname"
@make install -C dirname

clean:
@echo "\x1B[0;1;35m make\x1B[0m clean utilities/hello"
Expand Down Expand Up @@ -93,4 +97,6 @@ clean:
@echo "\x1B[0;1;35m make\x1B[0m clean utilities/rm"
@make clean -C rm
@echo "\x1B[0;1;35m make\x1B[0m clean utilities/ln"
@make clean -C ln
@make clean -C ln
@echo "\x1B[0;1;35m make\x1B[0m clean utilities/dirname"
@make clean -C dirname
23 changes: 23 additions & 0 deletions dirname/Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
PLATFORM=x86_64-lux
CCFLAGS=-Wall -c -O3
LDFLAGS=-llux
CC=x86_64-lux-gcc
LD=x86_64-lux-gcc
SRC:=$(shell find . -type f -name "*.c")
OBJ:=$(SRC:.c=.o)

all: dirname

%.o: %.c
@echo "\x1B[0;1;32m cc \x1B[0m $<"
@$(CC) $(CCFLAGS) -o $@ $<

dirname: $(OBJ)
@echo "\x1B[0;1;93m ld \x1B[0m dirname"
@$(LD) $(OBJ) -o dirname $(LDFLAGS)

install: dirname
@cp dirname ../out/

clean:
@rm -f dirname $(OBJ)
63 changes: 63 additions & 0 deletions dirname/dirname.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
/*
* luxOS - a unix-like operating system
* Omar Elghoul, 2024-25
*
* dirname: Implementation of the dirname command
*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>

int main(int argc, char **argv) {
if(argc < 2) {
fprintf(stderr, "usage: %s string...\n", argv[0]);
return EXIT_FAILURE;
}

char new[PATH_MAX];
const char *old;

for(int i = 1; i < argc; i++) {
old = argv[i];
memset(new, 0, PATH_MAX);

if((strlen(old) == 1) && (old[0] == '/')) {
new[0] = '/';
goto print;
}

if((strlen(old) == 2) && (old[0] == '/') && (old[1] == '/')) {
new[0] = '/';
goto print;
}

strcpy(new, old);

for(int j = strlen(new)-1; j >= 0; j--) {
if(new[j] == '/') new[j] = 0;
else break;
}

if(!strchr(new, '/')) {
sprintf(new, ".");
goto print;
}

for(int j = strlen(new)-1; j >= 0; j--) {
if(new[j] != '/') new[j] = 0;
else {
new[j] = 0;
break;
}
}

if(!strlen(new)) sprintf(new, "/");

print:
printf("%s\n", new);
}

return EXIT_SUCCESS;
}

0 comments on commit 26bd6e1

Please sign in to comment.