I just posted this question, but I made quite a few mistakes in the way that I copied my code--so I'm going to repost it.
I'm trying to recreate a head
command which prints the top of a file to standard output. I'm not sure if the command can take more options than -n
(user specifies number of lines they want to be printed) and -c
(user specifies number of chars they want to be printed), but those are the options I am implementing. I've finished most of the code, but can't quite get my program to print the correct number of lines when the -n
option is used. Here's my code for the -n
option:
char *buff = malloc(1024);
ssize_t szt = 0;
lines_read = 0;
fd = open(file.txt, O_RDONLY); // placeholder file.txt
while ((szt = read(fd, buff, sizeof(buff))) > 0) {
for (int j = 0; j < sizeof(buff); ++j) {
if (buff[j] == '\n') {
++lines_read;
if (lines_read > n) {
write(STDOUT_FILENO, buff, j);
break;
} // if
} // if
} // for
} // for
Here's a link to my entire file head.c file. head