函數聲明:char *fgets(char *str,int n,FILE *stream)
函數介紹:從指定的stream流中讀取一行,并把它存儲在str所指向的字符串中。當讀取到(n-1)個字符時,獲取讀取到換行符時,或者到達文件末尾時,他會停止。具體視情況而定。
函數參數:
l? str –- 這是一個指向字符數組的指針,該數組存儲了要讀取的字符串。
l? n – 這是讀取的最大的字符數(包括最后面的空字符),通常是使用str傳遞的數組長度。
l? stream – 這是指向FILE對象的指針,該FILE對象標識了要從中讀取的字符串。
返回值:如果成功,該函數返回相同的str參數,如果到達文件末尾或者沒有讀取到任何字符,str內容保持不變,并返回一個空指針。
?
實例:
/* fgets.c */ int main() {FILE *fp;char str[60];fp = fopen("file.txt","r");if(NULL == fp){perror("open the file error");return 0;}while(NULL != fgets(str,60,fp)){puts(str);}fclose(fp);return 0; }
/* file.txt */ this is first line this is second linethis is three line
輸出結果:
exbot@ubuntu:~/wangqinghe/Transducer/20190712/01$ ./fgets
this is first line
?
this is second line
?
?
?
this is three line
?
exbot@ubuntu:~/wangqinghe/Transducer/20190712/01$ gedit fgets.c file.txt
?
puts(str);//自帶“\n”
改為:printf(“%s”,str);
運行結果:
exbot@ubuntu:~/wangqinghe/Transducer/20190712/01$ ./fgets
this is first line
this is second line
?
this is three line