I am trying to read strings from a file that has each string on a new line but I think it reads a newline character once instead of a string and I don\'t know why. If I\'m going
As already stated, if there's enough room in the buffer, then fgets()
reads the data including the newline into the buffer and null terminates the line. If there isn't enough room in the buffer before coming across the newline, fgets()
copies what it can (the length of the buffer minus one byte) and null terminates the string. The library resumes reading from where fgets()
left off on the next iteration.
Don't mess with buffers smaller than 2 bytes long.
Note that gets()
removes the newline (but does not protect you from buffer overflows, so do not use it). If things go as currently planned, gets()
will be removed from the next version of the C standard; it will be a long time before it is removed from C libraries (it will just become a non-standard - or ex-standard - additional function available for abuse).
Your code should check each of the fgets()
function calls:
while (fgets(inimene[i].Enimi, 20, F1) != 0 &&
fgets(inimene[i].Pnimi, 20, F1) != 0 &&
fgets(inimene[i].Kood, 12, F1) != 0)
{
printf("i=%d\nEnimi=%s\nPnimi=%s\nKaad=%s", i, inimene[i].Enimi, inimene[i].Pnimi, inimene[i].Kood);
i++;
}
There are places for do/while loops; they are not used very often, though.