位置:首頁 > 高級語言 > C語言標準庫 > fscanf() - C語言庫函數

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|