两者主要在安全性上存在差别。
函数名: 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作为函数值返回。
gets()将删除新行符, fgets()则保留新行符.
要去掉fgets()最后带的“/0",只要用 s[strlen(s)-1]='/0';即可。
针对于fgets,还要再说两句,下面这种用法,是安全的判断文件读取结束或者出错的好方式,切忌不能使用while(!feof(fp)) ,还有对于fgets的第二个参数是最大能读取文件字符的个数,一般最大的长度是1024字节。
while(fgets(..., stream)){
/* ... */
}
if(ferror(stream)){
/* ... */
}