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'结束的。


你可能感兴趣的:(Linux菜鸟编程)