Skip to content

Creating a function that extracts one line at a time from a text file

Notifications You must be signed in to change notification settings

RealConrad/42get-next-line

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

17 Commits
 
 
 
 
 
 
 
 

Repository files navigation

📗 Get Next Line

A C library that reads a single line from a file descriptor at a time, allocating memory for the line dynamically.

This repository is coded in  

Features

  • Read lines from a file descriptor one line at a time.
  • Stops reading at the first newline character ('\n') or the end of file (EOF).
  • Dynamically alocate memory for the line, which must be freed by the caller.
  • Handles multiple file descriptors simultaneously, without losing reading context (see bonus part).
  • All functions have doxygen comments explaining their purpose in detail.
  • Handles edge cases such as empty files, invalid file descriptors and memory allocaiton errors.

Installation

  1. Clone the repository.
% git clone https://github.com/RealConrad/42get-next-line.git
  1. Remember to include get_next_line.h and/or get_next-line_bonus.h respectively in your c (source) files.
  2. Compile with get_next_line.c and get_next_line_utils.c and/or get_next_line_bonus.c and get_next_line_utils_bonus.c respectively.

Examples

An example on how to use the library:
File: main.c

#include "get_next_line.h"
#include <stdio.h>
#include <fcntl.h>

int main(int argc, char **argv)
{
    int fd;
    char *line;

    if (argc != 2)
    {
        printf("Usage: %s <filename>\n", argv[0]);
        return (1);
    }

    fd = open(argv[1], O_RDONLY);
    if (fd < 0)
    {
        printf("Error opening file");
        return (1);
    }

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

    close(fd);
    return (0);
}

Compiling and executing:

% gcc -Wall -Wextra -Werror -D BUFFER_SIZE=32 main.c get_next_line.c get_next_line_utils.c -o gnl_test
% ./gnl_test <filename>.txt

License

MIT

About

Creating a function that extracts one line at a time from a text file

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages