Linux下开发warning:"the `gets' function is dangerous and should not be used"

菜鸟(当然指的是笔者)最近在Linux下开发:socket异步通信。

client端实现输入时用了gets(),就出现感叹号:“the `gets' function is dangerous and should not be used.”

while (gets(sendbuf) != NULL) {
              //......
              write(sock, sendbuf, strlen(sendbuf));
              read(sock, recvbuf, sizeof(recvbuf));
	
              puts(recvbuf);
}


网上查找了gets函数的详细说明:
char * gets ( char * str );//Get string from stdin

Reads characters from stdin and stores them as a string into str until a newline character ('\n') or the End-of-File is reached.
The ending newline character ('\n') is not included in the string.

A null character ('\0') is automatically appended after the last character copied to str to signal the end of the C string.

Notice that gets does not behave exactly as fgets does with stdin as argument: First, the ending newline character is not included with gets while with fgets it is. And second, gets does not let you specify a limit on how many characters are to be read, so you must be careful with the size of the array pointed by str to avoid buffer overflows.

笔者过去都是在windows环境下编程开发,没有特别在意gets()函数的用法。

gets从stdin流中读取字符串,直至接受到换行符或EOF时停止,换行符不作为读取串的内容,读取的换行符被转换为null值,并由此来结束字符串。所以gets读入的字符串是以‘\0’结尾的。

导致warning的原因是Linux下的gcc编译器不支持gets。本质还是windows和linux在文件换行符上的编码不同,这方面想知道的朋友可以去这里详细了解。http://blog.csdn.net/wjcquking/article/details/6634504

一般的解决办法都是用fgets(cmd,len,stdin);

将从stdin中读取数据进cmd缓存区,字符串长度限制在len。而fgets()是以'\n'结束的。


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值