Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unistd.h read() function: How to read a file line by line?

Tags:

c

unix

What I need to do is use the read function from unistd.h to read a file line by line. I have this at the moment:

n = read(fd, str, size);

However, this reads to the end of the file, or up to size number of bytes. Is there a way that I can make it read one line at a time, stopping at a newline? The lines are all of variable length.

I am allowed only these two header files:

#include <unistd.h>
#include <fcntl.h>

The point of the exercise is to read in a file line by line, and output each line as it's read in. Basically, to mimic the fgets() and fputs() functions.

like image 868
Will Avatar asked Feb 27 '10 20:02

Will


2 Answers

Unfortunately the read function isn't really suitable for this sort of input. Assuming this is some sort of artificial requirement from interview/homework/exercise, you can attempt to simulate line-based input by reading the file in chunks and splitting it on the newline character yourself, maintaining state in some way between calls. You can get away with a static position indicator if you carefully document the function's use.

like image 179
Mark B Avatar answered Sep 20 '22 15:09

Mark B


You can read character by character into a buffer and check for the linebreak symbols (\r\n for Windows and \n for Unix systems).

like image 23
Otto Allmendinger Avatar answered Sep 21 '22 15:09

Otto Allmendinger