VS2017中使用fopen函数报错:This function or variable may be unsafe。win10下fopen使用需注意的问题总结

先贴代码:

#include 
#include 

int main() {

	char *info = "this is test";

	FILE *stream2;

	if ((stream2 = fopen("D:\\log.txt", "a+")) == NULL) // C4996
		printf("The file 'data2' was not opened\n");
	else
	   printf( "The file 'data2' was opened\n" );
	fwrite(info, sizeof(char), strlen(info), stream2);
	fclose(stream2);

	system("pause");

	return 0;
}

上面代码在VS2017中运行会报以下错误:
错误    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.   

因为VS2017默认使用更加安全的fopen_s函数,若要继续使用fopen,需要在 项目->属性->C/C++->SDL检查 中设置为否。

VS2017中使用fopen函数报错:This function or variable may be unsafe。win10下fopen使用需注意的问题总结_第1张图片

其次在fopen函数参数路径在Windows环境下可以使用 / 或者 \\ 作为分隔符,两种方式都行,但如果在cmd命令行中使用路径只能用\\

stream2 = fopen("D:\\log.txt", "a+") //正确
stream2 = fopen("D:/log.txt", "a+")  //正确
stream2 = fopen("D:\log.txt", "a+")  //错误

特别注意:不要直接在C盘下写入文件,win10在C盘写入文件需要权限的。如果将代码改为stream2 = fopen("C:\\log.txt", "a+"),程序运行也会出错,直接复制文件到C盘都会出现下面的提示。

VS2017中使用fopen函数报错:This function or variable may be unsafe。win10下fopen使用需注意的问题总结_第2张图片

最后一个问题是:盘符的名称是不区分大小写的,D:和d:是一样的,都能正常读取。

你可能感兴趣的:(C语言,C)