Skip to content

Commit

Permalink
head: implementation of the head command
Browse files Browse the repository at this point in the history
  • Loading branch information
jewelcodes committed Dec 4, 2024
1 parent f34f2be commit a901515
Show file tree
Hide file tree
Showing 3 changed files with 83 additions and 1 deletion.
8 changes: 7 additions & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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"
Expand All @@ -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
@make clean -C libctests
@echo "\x1B[0;1;35m make\x1B[0m clean utilities/head"
@make clean -C head
Binary file added head/head
Binary file not shown.
76 changes: 76 additions & 0 deletions head/head.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
/*
* luxOS - a unix-like operating system
* Omar Elghoul, 2024
*
* head: Implementation of the head command
*/

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

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;
}

0 comments on commit a901515

Please sign in to comment.