In this project, I created a function that returns every next line of a text file each time we call it. The prototype looks like this :
char *get_next_line(int fd)
{
...
return (line);
}
As you can see it takes a file descriptor as argument and returns a char string. The file descriptor corresponds to the open file you wanna read from. Here is an example of get_next_line function :
int main(void)
{
int fd;
fd = open("text.txt", O_RDWR);
/// we use printf directly to display the char string returned by get_next_line ///
printf("Here is the first line of the file text : %s", get_next_line(fd));
}
int main(void)
{
int fd;
fd = open("text.txt", O_RDWR);
printf("Here is the first line of the file text : %s", get_next_line(fd));
printf("Here is the second line of the file text : %s", get_next_line(fd));
printf("Here is the third line of the file text : %s", get_next_line(fd));
printf("Here is the fourth line of the file text : %s", get_next_line(fd));
printf("Here is the last line of the file text : %s", get_next_line(fd));
}
To make sure that our get_next_line function returns each time the very next line in a specific file we use a "static" variable that keeps track of the position in the text file after each function call. Here's a quick explanation from GeeksforGeeks to help you understand more static variables :
I'll conclude this part by talking about the benefits of such a function : Indeed, now that I can consistantly return the next line of a desired file, I can use it for example in a game project where GNL will help me read my map files and parse it correctly. So did I in so_long and cub3d graphic projects. Moreover, making this function helped me understand even more how to work with strings, files, and read function.