文件字符讀寫函數fscanf()和 fgets() 比較


 

一、 文件格式化讀入函數 fscanf()

 int  fscanf(文件指針,格式化字符串,輸入列表);

 返回值: 整形,輸入列表中定義字符串的個數。

 

1, 例如讀取字符串:

char  str1[256], str2[256];

FILE  *file;

int n,m;

n=fscanf(file,"%s%s",str1,str2);      \\n=2

m=fscanf(file,"%s%s\n",str1,str2);   \\m=2,格式字符串中可以加入格式控制符

 

2, fscanf()函數讀入開始和結束:

讀入開始:從第一個實字符開始,即從第一個非空格符‘ ’、非跳格符tab、非回車換行符‘\n’、非EOF開始。

讀入結束:讀入過程中遇到的第一個空格符‘ ’、跳格符tab 、 回車換行符‘\n’ 或者EOF。

 

3,  注意:fscanf()並不讀入結束符,也就是空格符、回車符、跳格符tab本身不會被輸入字符串。

 

4,舉例如下:

 

E盤下有文件  e:\\test.txt,文件內容如下:

endloop
endfacet next
triangle

 

程序實例case 1:

int main()
{
    FILE *file;
    file=fopen("e:\\test.txt","r");

    char str[256];
int n(0); if(1!=fscanf(file,
"%s",str)) //讀入字符串個數為1,所以返回值為1
return false;
long strLenth(0); strLenth=strlen(str); //字符串str長度為7,並未取入第一行末尾回車換行符;
//此時文件指針file指向第一行最后的回車
換行字符'\n'
 cout<<"lenth of str:"<<strLenth<<endl; //7
printf("%s",str); //"endloop"

printf(
"%c\n",fgetc(file)); //獲取並輸出test.txt文件第一行最后的回車換行字符'\n'
    printf("%c\n",fgetc(file)); //讀入並輸出test.txt文件第二行開頭字符'e'  

fclose(file);
}

 

 

 

程序實例case2:

int main()
{
     FILE *file;
    file=fopen("e:\\test.txt","r");

    char str1[256], str2[256];

    fscanf(file,"%*s"); //跳過第一個字符"endfacet",file指向第一行最后一個字符回車換行符'\n'

    if (2 != fscanf(file,"%s %s\n",str1,str2))  return false; 
//file執行向str1,str2讀入兩個字符串;由於fscanf()規定從第一個非空格、非回車換行符、非文件結尾開始讀入,
//所以file跳過當前指向的'\n',從第二行開始讀入;
讀入字符串個數為2,所以返回值為2; //因為輸入格式字符串"%s %s\n"最后加了回車控制符,所以file當前指向第二行第一個字符. printf("%s %s\n",str1,str2); //"endfacet next" printf("%c\n",fgetc(file)); //輸出test.txt文件第二行開頭字符't' fclose(file); }

 

 

二、從文件讀入一個字符串函數 fputs()

char *  fgets(str,n,fp);

返回值:返回字符串 str的首地址。

n為要求得到的字符數,但只能從文件fp輸入n-1個字符,第n個字符為自動加入的'/0'。

 

1, 例如:

 char *pCh;

 char str[128];

 FILE *file;

 pCh=fgets(str, 128, file);

 

2, fgets()讀取的開始和結束:

    fgets()讀入開始:所有非EOF開始的字符,即fgets()可以以空格‘ ’、跳格tab、回車換行符'\n'開始讀入。

    fgets()讀入結束:讀完n-1個字符之前,遇到換行‘\n’、文件結束EOF。

 

3, 注意:fgets()函數在讀完n-1個字符之前,可以讀入空格符' ', 回車符'/n',也可以以他們為開始讀入。

 

4, 舉例:

 

main()
{
       FILE *file;
    file=fopen("e:\\test.txt","r");

    char vmarker[256];
    fgets(vmarker,256,file); //讀入文件第一行字符 long strLenth(0);
    strLenth=strlen(vmarker);  //字符串長度為8,字符串取入第一行末尾回車符’\n‘
cout<<"lenth of vmarker:"<<strLenth<<endl; //8 printf("%s",vmarker); //輸出字符串"endloop\n",由於最后一個字符為'\n',執行回車換行 printf("%c\n",fgetc(file)); //獲取並輸出test.txt文件第二行開頭字符'e' fclose(file); }

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM