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

来源:互联网 发布:win7固态硬盘优化工具 编辑:程序博客网 时间:2024/06/07 03:49

今天在LINUX下编译C程序时,出现了一下警告:

In function ‘main’:warning: ‘gets’ is deprecated (declared at /usr/include/stdio.h:638) [-Wdeprecated-declarations]   gets(s);   ^/tmp/ccWcGgsb.o: In function `main':(.text+0x3a): warning: the `gets' function is dangerous and should not be used.


warning: the 'gets' function is dangerous and should not be used。这样的一个警告,在经过查阅资料以及自己的努力之后,才得知问题出在程序中使用了gets()函数,Linux 下gcc编译器不支持这个函数,解决办法是使用fgets,同时对程序做稍微的修改即可.

首先我们先对fgets()函数的基本用法做一个稍微的了解:

fgets(char * s,int size,FILE * stream);//eg:可以用fgets(tempstr,10,stdin)//tempstr 为char[]变量,10为要输入的字符串长度,stdin为从标准终端输入。

 

下面是关于树的一个小练习:

#include <stdio.h>#include <stdlib.h>struct tree{char info;struct tree *left;struct tree *right;};struct tree *root;struct tree *construct(struct tree *root, struct tree *r, char info);void print(struct tree *r);int main(void){char s[10];root = NULL;do{printf("请输入一个字符:");fgets(s, 10, stdin);/* gets(s); */root = construct(root, root, *s);}while(*s);print(root);return 0;}struct tree *construct(struct tree *root, struct tree *r, char info){if(!r){r = (struct tree *)malloc(sizeof(struct tree));if(!r){printf("内存分配失败!\n");exit (0);}r->left = NULL;r->right = NULL;r->info = info;if(!root){return r;}if(info < root->info){root->left = r;}else{root->right = r;}return root;}if(info < r->info){construct(r, r->left, info);}else{construct(r, r->right, info);}return root;}void print(struct tree *r){int i;if(!r){return;}print(r->left);printf("%c\n", r->info);print(r->right);}

 

以上我们只对gets()函数进行了修改,虽然编译过程中不会出现错误以及警告,但是在执行过程中你会发现没有一个标志(或状态)让程序跳出do..while循环,这是因为还一点重要的是gets从终端读入是的字符串是用\0结束的,而fgets是以\n结束的(一般输入都用ENTER结束),然后strcmp两者的时候是不会相等的!

所以我们还要对while中的判断条件进行一个稍微的修改,即改为while(*s && *s != '\n')  即可。

 

课外:
 这个问题应该是因为linux和 windows的文件在换行符上编码不一样导致的,linux的换行是\0,windows的换行是\13\0,是两个字符。

但是的文件应该是在windows下编译的,所以导致会出现两字符不匹配。建议可以在linux终端下,利用dos2unix filename,来将换行符处理一下,应该就OK了

 

0 0
原创粉丝点击