Posted on 2008-08-18 18:50
Prayer 閱讀(2676)
評論(0) 編輯 收藏 引用 所屬分類:
C/C++
函數名: fgets
功 能: 從流中讀取一字符串
用 法: char *fgets(char *string, int n, FILE *stream);
形參注釋:*string結果數據的首地址;n-1:一次讀入數據塊的長度,其默認值為1k,即1024;stream文件指針
序 例:
#include <string.h>
#include <stdio.h>
int main(void)
{
FILE *stream;
char string[] = "This is a test";
char msg[20];
/* open a file for update */
stream = fopen("DUMMY.FIL", "w+");
/* write a string into the file */
fwrite(string, strlen(string), 1, stream);
/* seek to the start of the file */
fseek(stream, 0, SEEK_SET);
/* read a string from the file */
fgets(msg, strlen(string)+1, stream);
/* display the string */
printf("%s", msg);
fclose(stream);
return 0;
}
fgets函數fgets函數用來從文件中讀入字符串。fgets函數的調用形式如下:fgets(str,n,fp);此處,fp是文件指針;str是存放在字符串的起始地址;n是一個int類型變量。函數的功能是從fp所指文件中讀入n-1個字符放入str為起始地址的空間內;如果在未讀滿n-1個字符之時,已讀到一個換行符或一個EOF(文件結束標志),則結束本次讀操作,讀入的字符串中最后包含讀到的換行符。因此,確切地說,調用fgets函數時,最多只能讀入n-1個字符。讀入結束后,系統將自動在最后加'\0',并以str作為函數值返回。