You are not understanding how fgets
works.
fgets
will read up to 3 characters (and not 4, because fgets
'\0'-terminates the buffer). If the newline '\n'
is among these 3,
fgets
will stop reading and writes the newline and returns, otherwise it
continues until the buffer is full.
Let's say the input is: This is a very long line\nThis is another line\n
,
then fgets
will read the first 3 characters and store 'T'
, 'h'
, 'i'
,
'\0
in the buffer. The next time fgets
reads the next 3 characters:
's'
, ' '
, 'i'
and store them in the buffer. Eventually it will reach to
the first newline, and stops reading there.
In general fgets
will try to read the max number of characters that the buffer can hold.
If the newline is among these characters, it stops reading and writes the newline
in the buffer as well. If the newline is not found among them, then fgets
will
stop when the buffer is full.
Whether fgets
reads a whole line depends on the size of the buffer, so even
with two consecutive calls of fgets
, you might not still getting the whole
line, as I showed you with the example above. That's why your assumption
I assume that setting a buffer to 4 would likely return the first four
characters of each line is wrong.
The only way to know if fgets
read a whole line is looking whether the newline was written in the buffer.
Also note that
if (feof(fp))
break ;
is not needed here, because fgets
will return NULL
when the end-of-file is
reached and no more characters can be read, the loop will end anyway, so doing
the extra check is pointeless.
And this
while(fgets(buf,4,fp) != NULL){
...
} while(1);
is the same as this:
while(fgets(buf,4,fp) != NULL){
...
}
while(1);
So after reading the whole file, you are entering in an endless loop.