INF: fscanf() Fails to Read Consecutive Lines

ID Number Q60336

5.10 6.00 6.00a 6.00ax 7.00 | 5.10 6.00 6.00a

MS-DOS | OS/2

Summary:

In Microsoft C versions 5.0, 5.1, 6.0, 6.0a, 6.0ax, and C/C++ version

7.0 if you try to read lines of text using fscanf() from a file opened

in text mode, and define [^\n] as the delimiter, your program will read

only the first line of the text file.

Sample Code

-----------

FILE *fin;

char Line[80];

while ( ( fscanf(fin,"%[^\n]",line) ) !=EOF )

{

printf("Line = %s \n",line);

}

More Information:

At first glance, the sample code appears to read and print lines from

a text file until the end of the file is reached. However, this is not

the case.

The fscanf() function reads up to but not including the delimiting

character. Therefore, the file stream is stopped at the first "\n" in

the file. Subsequent fscanf() calls fail because the file is still at

the first delimiting character and fscanf() will not move past it.

To move the file stream beyond the delimiting character, use one of

the following two workarounds:

- Place a fgetc() after the fscanf() to position the file pointer

past the "\n".

-or-

- Change the fscanf() call to the following:

fscanf(fin, "%[^\n]%*c", line)

This call automatically reads the next character.

The corrected code is as follows:

FILE *fin;

char Line[80];

while ( ( fscanf(fin,"%[^\n]",line) ) !=EOF )

{

fgetc(fin); // Reads in "\n" character and moves file

// stream past delimiting character

printf("Line = %s \n",line);

}

Additional reference words: 5.00 5.10 6.00 6.00a 6.00ax 7.00