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|