fscanf 函數(shù)原型為 int fscanf(FILE * stream, const char * format, [argument...]); 其功能為根據(jù)數(shù)據(jù)格式(format),從輸入流(stream)中讀入數(shù)據(jù),存儲到argument中,遇到空格和換行時結(jié)束。fscanf位于C標準庫頭文件中。1
fscanf 一般形式函數(shù)聲明int fscanf(FILE *stream, char *format[,argument...]);
參數(shù)stream-- 這是指向 FILE 對象的指針,該 FILE 對象標識了流。
format-- 這是 C 字符串,包含了以下各項中的一個或多個:空格字符、非空格字符和format 說明符。
format 說明符形式為**[=%[*][width][modifiers]type=]2**
功 能從一個流中執(zhí)行格式化輸入,fscanf遇到空格和換行時結(jié)束,注意空格時也結(jié)束。這與fgets有區(qū)別,fgets遇到空格不結(jié)束。
返回值整型,成功返回讀入的參數(shù)的個數(shù),失敗返回EOF(-1)。3
格式字符詳解format 說明符形式為[=%[*][width][modifiers]type=]****
具體講解如下:2
|| ||
fscanf 類型說明符
%d:讀入一個十進制整數(shù)。
%i :讀入十進制,八進制,十六進制整數(shù),與%d類似,但是在編譯時通過數(shù)據(jù)前置或后置來區(qū)分進制,如加入“0x”則是十六進制,加入“0”則為八進制。例如串“031”使用%d時會被算作31,但是使用%i時會算作25。
%u:讀入一個無符號十進制整數(shù)。
%f %F %g %G : 用來輸入實數(shù),可以用小數(shù)形式或指數(shù)形式輸入。
%x %X: 讀入十六進制整數(shù)。
%o': 讀入八進制整數(shù)。
%s : 讀入一個字符串,遇空字符‘\0'結(jié)束。
%c : 讀入一個字符。無法讀入空值??崭窨梢员蛔x入。1
附加格式說明字符表修飾符說明
L/l 長度修飾符 輸入"長"數(shù)據(jù)
h 長度修飾符 輸入"短"數(shù)據(jù)
程序例示例一#include #include 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);}輸出結(jié)果:
Read String1 |We|Read String2 |are|Read String3 |in|Read Integer |2014|示例二附:MSDN中例子
#include 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'); /*將指針設(shè)置至文件開頭*/ fseek(stream,0L,SEEK_SET); /*從文件中讀取數(shù)據(jù)*/ fscanf(stream,"%s",s); fscanf(stream,"%ld",&l); fscanf(stream,"%f",&fp); fscanf(stream,"%c",&c); /*輸出讀取的數(shù)據(jù)*/ printf("%s\n",s); printf("%ld\n",l); printf("%f\n",fp); printf("%c\n",c); fclose(stream); } return 0;}//這樣會有意外輸出本詞條內(nèi)容貢獻者為:
徐恒山 - 講師 - 西北農(nóng)林科技大學(xué)