Skip to content

aymenmarjan/get_next_line

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 

Repository files navigation

This project has been created as part of the 42 curriculum by amarjan.

get_next_line

Description

The get_next_line project consists of implementing a function that reads from a file descriptor and returns one line at a time.

Each call to the function returns the next line, including the newline character (\n) if it exists, until the end of the file is reached.

This project helps understand how file descriptors, the read() function, memory allocation, and static variables work in C.


Instructions

Compilation

Compile the project using the following flags:

cc -Wall -Wextra -Werror get_next_line.c get_next_line_utils.c main.c

Execution

This project provides a function, not a standalone program.

To test it, a small main.c can be written that:

  • opens a file and passes its file descriptor to get_next_line, or

  • uses file descriptor 0 to read from standard input.

The behavior of the function is independent of the test program used.

Algorithm Explanation

  • read() reads a fixed number of bytes defined by BUFFER_SIZE, not full lines.

  • A static buffer (stash) is used to store data that has been read but not yet returned.

  • The function keeps reading and appending data until a newline (\n) or EOF is found.

  • One line is extracted and returned.

  • Any remaining data is preserved for the next call.

A static variable is required to avoid losing unread data between calls, especially when a single read() call contains multiple lines.

BUFFER_SIZE

The implementation works correctly for:

  • BUFFER_SIZE = 1

  • Large values of BUFFER_SIZE

  • Values larger than the file size

The algorithm does not rely on a specific buffer size.

Resources

  • man 2 read

  • man 3 malloc

  • man 3 free

  • 42 get_next_line subject

AI Usage

AI tools were used to help understand concepts and edge cases.

Example Usage

while ((line = get_next_line(fd)) != NULL)
{
    printf("%s", line);
    free(line);
}

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages