本文介绍了格式与文件内容不匹配时fscanf的行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果文件内容与传递给 fscanf 的格式字符串不匹配,则在下一次调用 fscanf

If the contents of a file do not match the format string passed to fscanf, what happens on the next call to fscanf?

假设文件包含以下两行:

Suppose a file contains the following two lines:

9000 pig dog
4 5 2

程序试图解析打开的文件( fp )如此:

A program tries to parse the opened file (fp) as such:

int a = 1, b = 1, c = 1;
int x = 1, y = 1, z = 1;

fscanf(fp, "%d %d %d", &a, &b, &c);
fscanf(fp, "%d %d %d", &x, &y, &z);

我怀疑 a 现在会保留 9000 ,而 b 和 c 继续保持值 1 -但是 x , y 和 z ?

I suspect that a would now hold 9000 while b and c continue to hold the value 1 -- but what happens to x, y, and z?

C99 标准是否保证 x , y 和 z 将保留值 4 , 5 和 2 -还是保证文件流的位置指示符保留在左侧解析失败后未修改,导致 x 保留值 9000 而 y 和 z 保持值 1 ?

Does the C99 standard guarantee that x, y, and z will hold the values 4, 5, and 2 respectively -- or is the file stream's position indicator guaranteed to be left unmodified after a failed parse, causing x to hold the value 9000 while y and z hold on to the value 1?

推荐答案

4) fscanf 函数依次执行格式的每个指令。如果指令失败,如下面详述的
,函数将返回。失败被描述为输入失败(由于
出现编码错误或输入字符不可用),或匹配
失败(由于输入不当)。

4) The fscanf function executes each directive of the format in turn. If a directive fails, as detailed below, the function returns. Failures are described as input failures (due to the occurrence of an encoding error or the unavailability of input characters), or matching failures (due to inappropriate input).

5)由空格字符组成的指令是通过读取最多
个第一个非空格字符(仍未读取)的输入来执行的,或者直到不再有其他字符可以执行为止

5) A directive composed of white-space character(s) is executed by reading input up to the first non-white-space character (which remains unread), or until no more characters can be read.

9)从流中读取输入项,除非指定中包含 n 指定者。
输入项被定义为最长的输入字符序列,该序列不超过
任何指定的字段宽度,并且是匹配输入序列的前序。输入项之后的第一个字符(如果有的话)保持未读状态。

9) An input item is read from the stream, unless the specification includes an n specifier. An input item is defined as the longest sequence of input characters which does not exceed any specified field width and which is, or is a prefix of, a matching input sequence. The first character, if any, after the input item remains unread.

所以 a 将为9000, b 和 c 继续为1。流最多可读取(但不包括) 猪,因此第二个呼叫的第一个%d 立即失败,从而导致 x , y 和 z 保持1。

So a will be 9000 and b and c continue to be 1. The stream is read upto (but not including) pig, so the first %d of the second call immediately fails, causing x, y and z to remain 1.

这篇关于格式与文件内容不匹配时fscanf的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 05:23