本文介绍了在C中使用fopen_s的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在C语言中编程时遇到了问题,尤其是在Visual Studio中使用fopen时.我阅读了有关 fopen_s 函数的信息,并将以下行添加到了我的项目中,但是它仍然无法正常工作.

I have a problem with programming in C, especially with fopen in Visual Studio. I read about the fopen_s function and added the following line to my project, but it still doesn't work.

_CRT_SECURE_NO_WARNINGS

所以我尝试以这种方式使用 fopen_s :

So I tried using fopen_s in this way:

FILE *fp;
errno_t err;
if ((err = fopen_s(&fp, "C:/File.txt", "rt")) != 0)
    printf("File was not opened\n");
else
    fprintf(fp, "Date: %s, Time: %s, Score: %i \n", __DATE__, __TIME__, score);
fclose(fp);

它仍然崩溃.怎么了?

推荐答案

即使打开失败,您也使用 fclose 带有无效的 fp 值.至少在 else 分支周围添加 {} .

You use fclose with an invalid fp value, even if opening failed. Add {} around the else branch, at least.

许多开发人员认为,即使在其中包含一条语句的情况下,到处都使用大括号通常是个好主意.如果不这样做,就很容易犯这样的错误,即使对于有经验的开发人员也是如此.因此,也将它们放在 then 分支周围.

Many developers think it is generally a good idea to use braces everywhere, even with one statement inside them. It's so easy to make a mistake like this if you don't, even for experienced developers. So put them around the then branch too.

这篇关于在C中使用fopen_s的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 17:42