Latest web development tutorials

C library functions - fscanf ()

C standard library - <stdio.h> C standard library - <stdio.h>

description

C library functionint fscanf (FILE * stream, const char * format, ...) to read formatted input from the stream stream.

statement

Here is the fscanf () function's declaration.

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

parameter

  • stream - This is a pointer to FILE pointer to an object, the object identifier FILE flow.
  • format - This is a C string containing the following items in one or more of:space characters, non-space charactersand format specifiers.
    format specifier of the form[=% [*] [width ] [modifiers] type =], the specific explanation as follows:
参数描述
*这是一个可选的星号,表示数据是从流 stream 中读取的,但是可以被忽视,即它不存储在对应的参数中。
width这指定了在当前读取操作中读取的最大字符数。
modifiers为对应的附加参数所指向的数据指定一个不同于整型(针对 d、i 和 n)、无符号整型(针对 o、u 和 x)或浮点型(针对 e、f 和 g)的大小: h :短整型(针对 d、i 和 n),或无符号短整型(针对 o、u 和 x) l :长整型(针对 d、i 和 n),或无符号长整型(针对 o、u 和 x),或双精度型(针对 e、f 和 g) L :长双精度型(针对 e、f 和 g)
type一个字符,指定了要被读取的数据类型以及数据读取方式。具体参见下一个表格。

fscanf type specifier:

类型合格的输入参数的类型
c单个字符:读取下一个字符。如果指定了一个不为 1 的宽度 width,函数会读取 width 个字符,并通过参数传递,把它们存储在数组中连续位置。在末尾不会追加空字符。char *
d十进制整数:数字前面的 + 或 - 号是可选的。int *
e,E,f,g,G浮点数:包含了一个小数点、一个可选的前置符号 + 或 -、一个可选的后置字符 e 或 E,以及一个十进制数字。两个有效的实例 -732.103 和 7.12e4float *
o八进制整数。int *
s字符串。这将读取连续字符,直到遇到一个空格字符(空格字符可以是空白、换行和制表符)。char *
u无符号的十进制整数。unsigned int *
x,X十六进制整数。int *
  • Additional parameters - Depending on the format string, the function may require a series of additional parameters, each containing a value to be inserted, replacing the format specified in the parameters% each label.The number of parameters should be the same as the number of label%.

return value

If successful, the function returns the number of successfully matched and assigned. If you reach the end of the file or a read error occurs, it returns EOF.

Examples

The following example demonstrates the fscanf () function is used.

#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 2014", fp);
   
   rewind(fp);
   fscanf(fp, "%s %s %s %d", str1, str2, str3, &year);
   
   printf("Read String1 |%s|\n", str1 );
   printf("Read String2 |%s|\n", str2 );
   printf("Read String3 |%s|\n", str3 );
   printf("Read Integer |%d|\n", year );

   fclose(fp);
   
   return(0);
}

Let's compile and run the above program, which will result in the following:

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

C standard library - <stdio.h> C standard library - <stdio.h>