The 42 school's get_next_line project is where we learn to read from a file descriptor, as well as the use of static variables.
This function returns a single line from a given file descriptor. If called in a loop, get_next_line returns the entire contents of a file, line by line until it reaches the end of the file. It can be compiled specifying any buffer size.
This function is not a stand-alone program, its files must be included and compiled within another project.
Example main.c
:
int main(void)
{
int fd;
char *line;
fd = open("test.txt", O_RDONLY);
if (fd == -1)
{
perror("Erreur d'ouverture du fichier");
return (1);
}
while ((line = get_next_line(fd)) != NULL)
{
printf("Ligne lue : %s", line);
free(line);
}
close(fd);
return (0);
}
Compilation:
gcc -Wall -Wextra -Werror get_next_line.c get_next_line_utils.c -o get_next_line
BUFFER_SIZE
can be specified at compilation to override the default BUFFER_SIZE
:
gcc -Wall -Werror -Wextra -D BUFFER_SIZE=42 get_next_line.c get_next_line_utils.c -o get_next_line
Execution:
./get_next_line [file]
Output should show the entire contents of the given file.
Execution with stdin:
./a.out /dev/tty
Program will wait for input, then once the enter key is pressed, print out the input as well as get_next_line's output. The process can be killed with ctrl-c
.