您的位置:首页 > Web前端

gets和fgets的区别.

2012-05-22 22:37 671 查看
在gcc里,使用gets会产生一条警告:

 warning: the `gets' function is dangerous and should not be used.

曾经为了方便,就让它一直warning了,但是为什么gets是危险的呢。

在某国外论坛上看到这么一句话:
In order to use 
gets
 safely,
you have to know exactly how many characters that you will be reading so you can make your buffer large enough. You will only know that if you know exactly what data you will be reading.
为了安全地使用gets,你必须知道要读入字符的确切数目,或者你可以开辟足够大的缓冲区。前提是你知道你要读入什么样的数据。
gets
 doesn't
do any kind of check while getting bytes from stdin.
这句话揭示了重点:gets是不做越界检查的。它以'\0'来判断输入结束。
例如:
char array[] = "abcdefg";
gets(array);

你可以输入任意长的字符串,只要不是'\0'结尾,所以问题出现了,会发生对未知内存区域的改变,造成的后果是不可预期的。

既然gets不安全,就要找个替代品,那就是fgets.
Instead of using 
gets
,
you want to use 
fgets
,
which has the signature 
char*
fgets(char *string, int length, FILE * stream)
.
一旦限定长度length,那么不论输入多少,不用担心越界的问题了。超过length的部分是不会被读取的。但是要注意的是,fgets的读取是以'\n'为结尾的,和gets不同,可能在某些特殊场合带来不便。

为了程序的健壮性,对于gets,NEVER USE IT ANY MORE!
 
注:无论读取DOS还是UNIX的文件, 换行时都是以'\n'结尾, DOS格式时结尾不会添加'\r'.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息