Visual C代码尝试使用函数fopen_s(...)检查文件是否存在时发生崩溃!= NULL

时间:2014-02-08 23:56:35

标签: c visual-studio-2010 fopen

IDE:Visual C ++ 2010

编写执行简单字典攻击的应用程序。它会打开一个文件并在该文件中搜索特定的“字符串”(密码)。如果发现它会提醒用户'Pass Found!'别的'好!安全密码'

如果找不到此密码字典文件(d8.txt),则应显示错误消息。我读了fopen_s,如果文件不存在,它会抛出一个NULL指针。所以我编码:

if((fopen_s(&fp, "d8.txt", "r")) == NULL) {
         printf("Error! File Not Found!! ");

然而,当程序到达这一点时程序就崩溃了,MS Debug Library说“Debug Assertion Failed!Expression(str!= NULL)”

我做错了什么?

如果您需要,请填写完整的代码:

printf("\n[i] Now initiating a Dictionary Attack on the Password...");

FILE *fp;
if((fopen_s(&fp, "d8.txt", "r")) == NULL) {
         printf("Error! File Not Found!! ");
             printf("Is the d8 Dictionary present?");
             exit(1);
       }

while(fgets(FileTemp, 30, fp) != NULL) {
    if((strstr(FileTemp, UserPass)) != NULL) {
        PassFound=1;
    }

if(PassFound)
    printf("\nA match found!! Your Password is not strong!");
else
    printf("Good! Your Password was not Cracked by the Preliminary Dictionary Attack.");

2 个答案:

答案 0 :(得分:2)

fopen_s在失败时不返回空指针,但它将文件指针(fp)设置为null。返回值为0(成功时)和错误号(失败时)。所以你应该去:

   int errno=0;
   if((errno=fopen_s(&fp, "d8.txt", "r")) != 0) {
      // Here you can check errno to give more detailed error messages..
      printf("Error! File Not Found!! ");
   } else
   { // read the file ... }

检查以查看不同的错误编号:http://msdn.microsoft.com/en-us/library/t3ayayh1(v=vs.100).aspx 这里是fopen_s文档http://msdn.microsoft.com/en-us/library/z5hh6ee9(v=vs.100).aspx

答案 1 :(得分:1)

正确的方法:

if((fopen_s(&fp, "d8.txt", "r")) == 0)

fopen_s返回errno_t typedef int errno_t

0 file opened non zero file not opened

瓦尔特