Visual C Code Crashing when attempting to check if file exists using function fopen_s(...) != NULL

StackOverflow https://stackoverflow.com/questions/21653331

  •  08-10-2022
  •  | 
  •  

Question

IDE: Visual C++ 2010

Coding an app that performs a simple dictionary attack. It opens a file and searches for a particular 'string' (a password) in that file. If found it alerts the user 'Pass Found!' else 'Good! Secure password'

In case this password dictionary file is not found (d8.txt), it should display an error message. I read about fopen_s and it throws a NULL pointer if file not present. So I coded:

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

However the program just crashes when it reaches this point and MS Debug Library says "Debug Assertion Failed! Expression (str != NULL)"

What am I doing wrong?

The complete code if you need it:

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.");
Was it helpful?

Solution

fopen_s doesn't return null pointer on fail, but it sets the file pointer (fp) to null. The return value would be either 0 (on success) and an error number (on fail). So you should go for:

   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 ... }

Check to see different error numbers: http://msdn.microsoft.com/en-us/library/t3ayayh1(v=vs.100).aspx and here for fopen_s documentation http://msdn.microsoft.com/en-us/library/z5hh6ee9(v=vs.100).aspx

OTHER TIPS

The correct way:

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

fopen_s returns errno_t which is typedef int errno_t.

0 file opened non zero file not opened

valter

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top