reads n bytes at a time and returns the next line of input
git clone
Log | Files | Refs | README (1684B)

      1 # get_next_line
      3 | Resource | Link |
      4 | - | -
      5 home | <>
      6 code | <>
      7 bugs | <>
      8 email | <>
     10 The goal of this exercise is to write a function `get_next_line` which will
     11 read a constant amount of bytes at a time from a file descriptor until it
     12 detects a newline. It should then return a copy of the whole line while keeping
     13 the excess bytes in a safe place. A successive call will return the next line
     14 or NULL if there is nothing left to read.
     16 Allowed functions: syscalls `read`, `malloc` and `free`.
     18 ## Example
     20 Let's say `GNL_READ_SIZE` is 4.
     22 ```bash
     23 gcc *.c
     24 echo -n 'hello\nworld\n' | ./a.out
     25 ```
     27 (The main loop is in `example.c`)
     29 At first read, we get `hell` into our buffer of size `GNL_READ_SIZE`. Since
     30 there is no delimeter `\n` in there, we append the whole thing to our result
     31 string.
     33 At second read, we get `o\nwo`, since there is a delimeter in here, we append
     34 the first part to our result string. Then we shift the whole buffer to the left
     35 until it looks like `wo`. We then return our result string.
     37 A second call is issued. Our result string is empty again.
     39 Because our buffer isn't empty and doesn't content any delimeter, we append its
     40 content to our result string. Then we read for a third time. We get `rld\n`.
     41 Since there is a delimeter here, we append `rld` to our result string and we
     42 shift the buffer until after the `\n`. We return our result string.
     44 A third call is issued.
     46 Since we reached the End of input, read(2) will return 0. get_next_line() will
     47 then return NULL. It's the end of our main loop.