我试图在 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;
}
有人好心帮我解决这个问题。我已经评论了我尝试过的所有可能性。 谢谢!
最佳答案
raw scanf("%s")
与 gets() 一样危险(两者都暴露于缓冲区溢出)。您应该改用 fgets()
,它会限制字符串的长度。
gets() 和 fgets() 之间的另一个区别是后者将 '\n'
放在字符串中,虽然乍一看很烦人,但您可以看到该行是否被截断了。你应该做的是:
- 使用 fgets()
- 求
'\n'
- 如果存在,则该行足够小以适合缓冲区。只需将
'\n'
替换为'\0'
即可。 - 如果不存在,则用户键入的行比缓冲区长。根据情况,您对此是否满意。但在这两种情况下,您都必须完成对行的读取(读入新缓冲区或简单地通过循环调用
getchar()
直到获得'\n'
或EOF
) 在你下一次输入之前。
关于c - 在 Unix 下无法在 C 中工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16162161/