Posted on 2008-08-18 18:50
Prayer 閱讀(2676)
評(píng)論(0) 編輯 收藏 引用 所屬分類:
C/C++
函數(shù)名: fgets
功 能: 從流中讀取一字符串
用 法: char *fgets(char *string, int n, FILE *stream);
形參注釋:*string結(jié)果數(shù)據(jù)的首地址;n-1:一次讀入數(shù)據(jù)塊的長度,其默認(rèn)值為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函數(shù)fgets函數(shù)用來從文件中讀入字符串。fgets函數(shù)的調(diào)用形式如下:fgets(str,n,fp);此處,fp是文件指針;str是存放在字符串的起始地址;n是一個(gè)int類型變量。函數(shù)的功能是從fp所指文件中讀入n-1個(gè)字符放入str為起始地址的空間內(nèi);如果在未讀滿n-1個(gè)字符之時(shí),已讀到一個(gè)換行符或一個(gè)EOF(文件結(jié)束標(biāo)志),則結(jié)束本次讀操作,讀入的字符串中最后包含讀到的換行符。因此,確切地說,調(diào)用fgets函數(shù)時(shí),最多只能讀入n-1個(gè)字符。讀入結(jié)束后,系統(tǒng)將自動(dòng)在最后加'\0',并以str作為函數(shù)值返回。