fscanf() - C语言库函数

C库函数 int fscanf(FILE *stream, const char *format, ...) 从流中读取的格式输入。

声明

以下是 fscanf() 函数的声明。

int fscanf(FILE *stream, const char *format, ...)

参数

  • stream -- 这是一个文件对象的标识流的指针。

  • format -- 这是C字符串,其中包含一个或多个以下项目:空白字符,非空白字符和格式说明符。格式规范将 [=%[*][width][modifiers]type=], 详细说明如下:

参数 描述
* 这是一个可选的星号表示该数据是从流中被读取的,但忽略,即,它不会存储在相应的参数。
width 这指定在当前读出操作被读取的最大字符数
modifiers Specifies a size different from int (in the case of d, i and n), unsigned int (in the case of o, u and x) or float (in the case of e, f and g) for the data yiibaied by the corresponding additional argument: h : short int (for d, i and n), or unsigned short int (for o, u and x) l : long int (for d, i and n), or unsigned long int (for o, u and x), or double (for e, f and g) L : long double (for e, f and g)
type 的字符,指定将要读取的数据的类型以及它是如何被读取。请参阅下表。

fscanf类型说明:

类型 合格输入 参数类型
c Single character: Reads the next character. If a width different from 1 is specified, the function reads width characters and stores them in the successive locations of the array passed as argument. No null character is appended at the end. char *
d Decimal integer: Number optionally preceeded with a + or - sign int *
e,E,f,g,G Floating yiibai: Decimal number containing a decimal yiibai, optionally preceeded by a + or - sign and optionally folowed by the e or E character and a decimal number. Two examples of valid entries are -732.103 and 7.12e4 float *
o OctalInteger: int *
s String of characters. This will read subsequent characters until a whitespace is found (whitespace characters are considered to be blank, newline and tab). char *
u Unsigned decimal integer. unsigned int *
x,X Hexadecimal Integer int *
  • additional arguments -- 根据格式字符串,函数可能会想到一系列的额外的参数,每个包含一个值,而不是插入的格式参数中指定的标记每个%,如果有的话。应该有相同数量的%预期值的标签的数量的这些参数。

返回值

此函数返回成功匹配,分配的输入项目的数量,它可以是少于提供了在一个早期的匹配失败的情况下,甚至可以为零。

例子

下面的例子演示了如何使用fscanf() 函数。

#include <stdio.h>#include <stdlib.h>int main(){ char str1[10], str2[10], str3[10]; int year; FILE * fp; fp = fopen ("file.txt", "w+"); fputs("We are in 2012", fp); rewind(fp); fscanf(fp, "%s %s %s %d", str1, str2, str3, &year); printf("Read String1 |%s|", str1 ); printf("Read String2 |%s|", str2 ); printf("Read String3 |%s|", str3 ); printf("Read Integer |%d|", year ); fclose(fp); return(0);}

让我们编译和运行上面的程序,这将产生以下结果:

Read String1 |We|Read String2 |are|Read String3 |in|Read Integer |2012|