Reputation: 311
I'm trying for hours to find the answer for this question i've got in university. I tried running this with writing a file with two lines of : hello world and it reads the file perfectly, So i cant find the answer. I would appreciate your help !
A student wrote the next function for reading a text file and printing it exactly as it is.
void ReadFile(FILE *fIn)
{
char nextLine[MAX_LINE_LENGTH];
while(!feof(fIn))
{
fscanf(fIn,"%s",nextLine);
printf("%s\n",nextLine);
}
}
What are the two errors in this function?
You can assume that each line in the file is not longer than MAX_LINE_LENGTH characters, and that it is a text file that contains only alphabet characters, and that each line is terminated by '\n'.
Thanks.
Upvotes: 1
Views: 131
Reputation: 2660
A correct way of doing that is:
void ReadFile(FILE *fIn)
{
char nextLine[MAX_LINE_LENGTH];
while(fgets(nextLine, MAX_LINE_LENGTH, fIn)) {
printf("%s", nextLine);
}
}
As some have posted using feof to control a loop is not a good idea nor using fscanf to read lines.
Upvotes: 1
Reputation: 9904
The main error is that fsacnf( fIn, "%s", nextLine )
doesn't scan a complete line.
From man page:
s Matches a sequence of non-white-space characters; the next pointer must be a pointer to character array that is long enough to hold the input sequence and the terminating null byte ('\0'), which is added automatically. The input string stops at white space or at the maximum field width, whichever occurs first.
Thus if you have a line "a b" the first fscanf()
will scan just "a" and the second one "b" and both are printed in two different lines. You can use fgets()
to read a whole line.
The second one is maybe that it's stated "each line in the file is not longer than MAX_LINE_LENGTH characters" but nextLine
can contain atmost MAX_LINE_LENGTH-1
characters (+ '\0'
). That problem becomes even more important if you replace fscanf()
by fgets()
because than nextLine
must have also capacity to store '\n'
or '\r\n'
(depending on the platform you're on)
Upvotes: 1
Reputation: 2727
It discards white space. Try adding multiple spaces and tabs.
It may evaluate a stream more than once, and If there is a read error, the loop never terminates.
See: Why is “while ( !feof (file) )” always wrong?
Reading strings via scanf is dangerous. There is no bounds checking. You may read past you MAX_LINE_LENGTH.(and boom! Segfault)
Upvotes: 1