我试图在Unix下使用gets
函数在C语言中输入一个字符串,它不起作用!
它显示以下警告:
warning: the `gets' function is dangerous and should not be used.
如果我运行该程序,我没有得到输入字段。 代码是
#include<stdio.h>
int main()
{
int i;
char ch,newfile[10],content[100];
FILE *create;
printf("Enter New File Name to Create : ");
scanf("%s",newfile);
create=fopen(newfile,"w+");
printf("\nEnter Contents for %s : ",newfile);
//fgets(content,sizeof content,stdin);
//scanf("%s",&content);
//gets(content);
for(i=0;i<100;i++)
{
if(content[i]!='\0')
{
ch=content[i];
putc(ch,create);
}
else
break;
}
printf("\nYour File Is Created\n");
return 0;
}
有人帮我解决这个问题。我评论过我试过的所有可能性。 谢谢!
答案 0 :(得分:5)
raw scanf("%s")
和gets()一样危险(两者都暴露在缓冲区溢出中)。您应该使用fgets()
代替,这会限制字符串的长度。
gets()和fgets()之间的另一个区别是后者将'\n'
放入字符串中,虽然乍看之下令人烦恼,但您可以查看该行是否被截断。你应该做的是:
'\n'
'\n'
替换为'\0'
,您就是黄金。getchar()
,直到您获得'\n'
或EOF
)下一步输入。答案 1 :(得分:1)
第一个scanf不消耗行尾字符 - 你可以通过输入说“foo bar”作为文件名来研究它。
下一行的格式应为scanf("\n%99s", content);
- 注意前面的'\ n'来读取换行符,并注意防护99以防止缓冲区溢出。仍然不幸的是,如果用“foo bar”作为文件名,这种方法不足以产生预期的结果。反直觉地'bar'被读作内容。
最后gets
遇到与以前相同的问题。 (+主要问题,它没有防止缓冲区溢出。)