大网数据广告活动
Web服务器与PHP

Fscanf function doesn't read consecutive lines

· 52CE 我爱测

This article describes a problem that occurs when you read lines of text by using the Fscanf function.

This article describes a problem that occurs when you read lines of text by using the Fscanf function.

Original product version:   Visual C
Original KB number:   60336

Summary

When a file is open in text mode, an attempt to read lines of text by using the Fscanf function may fail and only one line of text is read from the file. The delimiter is set to [^\n]. The Fscanf function reads up to but does not include the delimiting character. Therefore, the file stream stops at the first \n in the file. Subsequent Fscanf function calls fail because the file pointer remains at the delimiting character and the Fscanf function cannot advance the function pointer past it. To move the file pointer past the delimiting character, use one of the following two methods:

  • Update the code to use the following Fscanf function call:

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

    The %*c format specifier reads one character from the input stream but does not assign it to any of the parameters in the fscanf function call.

  • Call the Fgetc function after the Fscanf function call to move the file pointer beyond the \n character.

The following code sample demonstrates this problem. The code sample should read and print lines from a text file until it reaches EOF. However, the code sample reads only the first line from the file. Since the end of file character has not been found, the code sample runs in an infinite loop if the file stream contains a \n character.

Code sample

FILE *stream;
char line[80];

while ((fscanf(stream, "%[^\n]", line))!= EOF )
{
    printf("Line = %s \n",line);
}

The following code example demonstrates the second method above to work around this problem:

FILE *stream;
char line[80];

while ((fscanf(stream, "%[^\n]", line))!= EOF)
{
    fgetc(stream); // Reads in '\n' character and moves file
    // stream past delimiting character
    printf("Line = %s \n", line);
}

Source: Microsoft Learn / IT Pro troubleshooting by Microsoft and contributors. Documentation licensed CC BY 4.0. Code samples are covered by the MIT License. Converted from Markdown, with links normalized and embedded media omitted.

资料来源与适用范围

资料来源
Microsoft Learn / IT Pro troubleshooting
适用范围
See source applicability · Source date 10/27/2020
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY 4.0 (documentation), MIT (code samples)

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。