C庫(kù)函數(shù) int fscanf(FILE *stream, const char *format, ...) 從流中讀取的格式輸入。
以下是 fscanf() 函數(shù)的聲明。
int fscanf(FILE *stream, const char *format, ...)
stream -- 這是一個(gè)文件對(duì)象的標(biāo)識(shí)流的指針。
format -- 這是C字符串,其中包含一個(gè)或多個(gè)以下項(xiàng)目:空白字符,非空白字符和格式說(shuō)明符。格式規(guī)范將 [=%[*][width][modifiers]type=], 詳細(xì)說(shuō)明如下:
參數(shù) | 描述 |
---|---|
* | 這是一個(gè)可選的星號(hào)表示該數(shù)據(jù)是從流中被讀取的,但忽略,即,它不會(huì)存儲(chǔ)在相應(yīng)的參數(shù)。 |
width | 這指定在當(dāng)前讀出操作被讀取的最大字符數(shù) |
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 | 的字符,指定將要讀取的數(shù)據(jù)的類型以及它是如何被讀取。請(qǐng)參閱下表。 |
fscanf類型說(shuō)明:
類型 | 合格輸入 | 參數(shù)類型 |
---|---|---|
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 -- 根據(jù)格式字符串,函數(shù)可能會(huì)想到一系列的額外的參數(shù),每個(gè)包含一個(gè)值,而不是插入的格式參數(shù)中指定的標(biāo)記每個(gè)%,如果有的話。應(yīng)該有相同數(shù)量的%預(yù)期值的標(biāo)簽的數(shù)量的這些參數(shù)。
此函數(shù)返回成功匹配,分配的輸入項(xiàng)目的數(shù)量,它可以是少于提供了在一個(gè)早期的匹配失敗的情況下,甚至可以為零。
下面的例子演示了如何使用fscanf() 函數(shù)。
#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); }
讓我們編譯和運(yùn)行上面的程序,這將產(chǎn)生以下結(jié)果:
Read String1 |We| Read String2 |are| Read String3 |in| Read Integer |2012|