diff --git a/Makefile b/Makefile index 1bbaa97..1a744a3 100644 --- a/Makefile +++ b/Makefile @@ -17,6 +17,8 @@ all: @make -C luxfetch @echo "\x1B[0;1;35m make\x1B[0m utilities/libctests" @make -C libctests + @echo "\x1B[0;1;35m make\x1B[0m utilities/head" + @make -C head install: @mkdir -p out @@ -38,6 +40,8 @@ install: @make install -C luxfetch @echo "\x1B[0;1;35m make\x1B[0m install utilities/libctests" @make install -C libctests + @echo "\x1B[0;1;35m make\x1B[0m install utilities/head" + @make install -C head clean: @echo "\x1B[0;1;35m make\x1B[0m clean utilities/hello" @@ -57,4 +61,6 @@ clean: @echo "\x1B[0;1;35m make\x1B[0m clean utilities/luxfetch" @make clean -C luxfetch @echo "\x1B[0;1;35m make\x1B[0m clean utilities/libctests" - @make clean -C libctests \ No newline at end of file + @make clean -C libctests + @echo "\x1B[0;1;35m make\x1B[0m clean utilities/head" + @make clean -C head \ No newline at end of file diff --git a/head/head b/head/head new file mode 100755 index 0000000..2d8feba Binary files /dev/null and b/head/head differ diff --git a/head/head.c b/head/head.c new file mode 100644 index 0000000..7defec6 --- /dev/null +++ b/head/head.c @@ -0,0 +1,76 @@ +/* + * luxOS - a unix-like operating system + * Omar Elghoul, 2024 + * + * head: Implementation of the head command + */ + +#include +#include +#include +#include + +int n = 10; +int totalLines = 0; +char *line = NULL; + +int head(FILE *input) { + int errors = 0; + + if(line) free(line); + line = NULL; + size_t lineSize = 4096; + + while(totalLines < n) { + getline(&line, &lineSize, input); + if(!line) { + errors++; + } else { + printf("%s", line); + totalLines++; + } + + if(feof(input)) break; + } + + return errors; +} + +int main(int argc, char **argv) { + opterr = 0; + int opt; + + while((opt = getopt(argc, argv, "n:")) != -1) { + if(opt == 'n') { + n = atoi(optarg); + } else if(opt == ':') { + fprintf(stderr, "%s: option -%c requires an operand\n", argv[0], optopt); + return -1; + } else { + fprintf(stderr, "%s: invalid option -- %c\n", argv[0], optopt); + fprintf(stderr, "usage: %s [-u] [file ...]\n", argv[0]); + return -1; + } + } + + int retval = 0; + FILE *input; + + if(optind < argc) { + for(int i = optind; i < argc; i++) { + input = fopen(argv[i], "r"); + if(!input) { + fprintf(stderr, "%s: cannot open %s for reading\n", argv[0], argv[i]); + retval++; + continue; + } + + retval += head(input); + } + } else { + input = stdin; + retval += head(input); + } + + return retval; +} \ No newline at end of file