This project is about programming a function that returns a line read from a file descriptor.
_This project introduces the concepts of static variables, dynamic memory allocation, file descriptors and macros while solving one simple task: that of using the Linux standard function
read()
to scan a file for single lines (i.e. strings of chars with a single trailing\n
(new line character)).
-
get_next_line.c
Function implementation.ft_found_error
finds an error in inputft_free
de-allocate the memoryft_slice
slice the string into piecesft_substr
returns a substring from a string
-
get_next_line_utils.c
Auxiliary functions (project requirement).ft_strlen
calculate the length of a stringft_strchr
locate character in stringft_strjoin
concatenates two stringsft_strlcpy
concatenate string to an specific sizeft_strdup
creates a dupplicate for the string passed as parameter
-
get_next_line.h
Header file. -
main.c
Printing loop iterating over the file : calls get_next_line to fetch each line, then prints. -
*_bonus.c
The files is exact copies of corresponding files but with the challenge you can read from the file descriptors 3, 4 and 5, to doing able to read from a different fd per call without losing the reading thread of each file descriptor or returning a line from another.
This project requires GNU Compiler Collection and GNU Make compiler.
❗️| Make sure you have all the required tools installed on your local machine then continue with these steps.
This function is not a stand-alone program, its files must be included and compiled within another project.
0. Download the archives
Download the archives and go to the folder directory:
# Clone the repository
$ git clone https://github.com/mewmewdevart/get_next_line
# Enter into the directory
$ cd get_next_line/src/
1. Using it in your code
To use the function in your code, simply include its header:
#include "get_next_line.h"
And create a main with some inserts.
Example main.c
:
#include "get_next_line.h"
#include <stdio.h>
#include <fcntl.h>
int main(int argc, char **argv)
{
int fd;
char *line;
(void)argc;
fd = open(argv[1], O_RDONLY);
if (fd == -1)
{
printf("open() error\n");
return (1);
}
line = "";
while (line != NULL)
{
line = get_next_line(fd);
printf("%s", line);
free(line);
}
fd = close(fd);
if (fd == -1)
{
printf("close() error\n");
return (1);
}
printf("%d", fd);
return (0);
}
2. Compilation
When compiling your code, add the source files and the required flag:
$ gcc get_next_line_utils.c get_next_line.c main.c -D BUFFER_SIZE=<size> -o get_next_line
Here BUFFER_SIZE
determines the size of the buffer used to read the file (in other words, how manny chars shall be read at once with every read()
call).
To run the program, enter the following in the command prompt:
$ ./get_next_line [file.txt]
Output should show the entire contents of the given file followed by a newline \n.
Developed with love 💜 by Larissa Cristina Benedito (Mewmew/Larcrist).