Similarly you ca read line-by-line:
char buf[MAXLINE];
// ...
while((fgets(buf,MAXLINE,stdin)) != NULL) {
do_something(buf);
}
Since fgets
copies the detected newline character, you can detect
end of line by checking the second to last buffer element. You can use
realloc
to resize the buffer (be sure you keep a pointer to the beginning of the buffer, but pass buf+n
, to the next fgets, where n
is the number of read characters). From the standard regarding fgets
:
Reads characters from stream and stores them as a C string into str until (num-1) characters have been read or either a newline or the end-of-file is reached, whichever happens first. A newline character makes fgets stop reading, but it is considered a valid character by the function and included in the string copied to str.
Alternatively, you could read the whole file in one go using fread() (see example following the link).