-
fscanf
鎖定
- 中文名
- fscanf
- 外文名
- fscanf
- 標準庫
- <stdio.h>
- 應 用
- C語言中基本的文件操作
- 函數名
- fscanf
- 功 能
- 用於讀取數據
fscanffscanf 一般形式
fscanf函數聲明
int fscanf(FILE *stream, char *format[,argument...]);
fscanf參數
- stream-- 這是指向 FILE 對象的指針,該 FILE 對象標識了流。
fscanf功 能
從一個流中執行格式化輸入,fscanf遇到空格和換行時結束,注意空格時也結束。這與fgets有區別,fgets遇到空格不結束。
fscanf返回值
fscanf格式字符詳解
format 説明符形式為[=%[*][width][modifiers]type=]
參數 | 描述 |
---|---|
* | 這是一個可選的星號,表示數據是從流 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 類型説明符
%d:讀入一個十進制整數。
%i :讀入十進制,八進制,十六進制整數,與%d類似,但是在編譯時通過數據前置或後置來區分進制,如加入“0x”則是十六進制,加入“0”則為八進制。例如串“031”使用%d時會被算作31,但是使用%i時會算作25。
%u:讀入一個無符號十進制整數。
%f %F %g %G : 用來輸入實數,可以用小數形式或指數形式輸入。
%x %X: 讀入十六進制整數。
%o': 讀入八進制整數。
%s : 讀入一個字符串,遇空字符‘\0'結束。
附加格式説明字符表修飾符説明
L/l 長度修飾符 輸入"長"數據
h 長度修飾符 輸入"短"數據
fscanf程序例
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 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); }
輸出結果:
Read String1 |We| Read String2 |are| Read String3 |in| Read Integer |2014|
fscanf示例二
附:MSDN中例子
#include <stdio.h> FILE *stream; int main(void) { long l; float fp; char s[81]; char c; stream = fopen("fscanf.out", "w+"); if(stream==NULL) printf("The file fscanf.out was not opened\n"); else { fprintf(stream,"%s%ld%f%c","a-string", 65000,3.14159, 'x'); /*將指針設置至文件開頭*/ fseek(stream,0L,SEEK_SET); /*從文件中讀取數據*/ fscanf(stream,"%s",s); fscanf(stream,"%ld",&l); fscanf(stream,"%f",&fp); fscanf(stream,"%c",&c); /*輸出讀取的數據*/ printf("%s\n",s); printf("%ld\n",l); printf("%f\n",fp); printf("%c\n",c); fclose(stream); } return 0; }//這樣會有意外輸出