我正在制作一个程序,它将字符作为输入读取,然后将它们输出到用户指定的文件中。我认为它正在工作,但现在它无法编译。这是代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void main()
{
int c = 0;
char FileName[100] = "";
FILE *fp;
printf("Please input the title of the file you're interested in: ");
scanf("%100s", FileName);
fp = fopen(FileName, "w");
if (fp == NULL)
{
perror(NULL);
exit(0);
}
printf("Please input what you want in your file \n(Press Ctrl+Shift+A to
end the program):");
for (c = getchar(); c != 1; c = getchar())
{
if (c == '\n')
printf("");
fputc(c, fp);
}
if (c == 1);
{
printf("\nCtrl+Shift+A is a correct ending.\n\n");
}
fclose(fp);
}
在我试图找出问题时,我发现问题出现在FILE * fp和fopen上。当注释掉文件引用时,代码至少会编译。我的输出告诉我使用fopen_s(),但我不确定该函数是如何工作的,或者我的当前代码是否可以使用它,因为它不能用于fopen()。如果有帮助,我正在使用Microsoft Visual Studio。我没有收到错误消息,但输入的内容是:
1>------ Build started: Project: Project1, Configuration: Debug Win32 ------
1>Exercise2.c
1>c:\users\djmcn\documents\visual studio 2017\projects\1.9\exercise2.c(18):
error C4996: 'scanf': This function or variable may be unsafe. Consider
using scanf_s instead. To disable deprecation, use
_CRT_SECURE_NO_WARNINGS. See online help for details.
1>c:\program files (x86)\windows
kits\10\include\10.0.16299.0\ucrt\stdio.h(1272): note: see declaration of
'scanf'
1>c:\users\djmcn\documents\visual studio 2017\projects\1.9\exercise2.c(20):
error C4996: 'fopen': This function or variable may be unsafe. Consider
using fopen_s instead. To disable deprecation, use
_CRT_SECURE_NO_WARNINGS. See online help for details.
1>c:\program files (x86)\windows
kits\10\include\10.0.16299.0\ucrt\stdio.h(207): note: see declaration of
'fopen'
1>Done building project "Project1.vcxproj" -- FAILED.
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
答案 0 :(得分:0)
这是Visual Studio中Microsoft编译器所独有的。此代码将使用GCC进行编译。
您可以关闭警告,使用其他编译器,也可以使用scanf_s和fopen_s。如果您被提交到VS,请使用他们的scanf_s和fopen_s标准。
这是关于scanf_s和scanf之间差异的另一个StackOverflow答案的链接:Difference between scanf and scanf_s
这是关于fopen_s和fopen之间区别的StackOverflow答案:fopen / fopen_s and writing to files
您可以在此处找到scanf_s的文档:https://msdn.microsoft.com/en-us/library/w40768et.aspx
fopen_s here: https://msdn.microsoft.com/en-us/library/z5hh6ee9.aspx
祝你好运。答案 1 :(得分:0)
一般来说,我建议有经验的工程师遵循编译器的建议 - scanf是不安全的,因为即使是最聪明的人也会错误地使用这些旧的C运行时函数创建安全漏洞(缓冲区溢出)。
但是,由于您刚刚开始学习,我将向您展示如何指示Visual Studio编译器不要错误地解决这些类型的问题。
在Visual Studio的“解决方案资源管理器”中,右键单击“项目”标题,然后从显示的上下文菜单中选择“属性”。从项目的“属性页”中,导航到C / C ++设置,然后在列表中找到“预处理器”选项。点击它。从那里,有一行用于定义预处理器定义。在您的情况下,添加“_CRT_SECURE_NO_WARNINGS”(带分号分隔符)。
更简单的方法是在源文件的顶部添加此行:
#define _CRT_SECURE_NO_WARNINGS