Kaan Binen
Kaan Binen

Reputation: 133

when trying to write file fprintf does not work

I am just trying to open and write something in file but when visual studio tries to execute fprintf program crashes here is my code

#include<stdlib.h>
int main()
{
    FILE* fPointer;
    fPointer = fopen_s(&fPointer,"‪C:\\asd.txt","w");
    fprintf(fPointer, "If ı can read this then ı can create for loop");
    fclose(fPointer);
    return 0;
}

here is the error message : Access violation writing location 0x0000003A.

Upvotes: 4

Views: 107

Answers (3)

Jahangir
Jahangir

Reputation: 161

fopen_s returns the error code if it failed to create file pointer. You have to check error value before file pointer use.

Upvotes: 0

Andreas Wenzel
Andreas Wenzel

Reputation: 24726

In contrast to fopen, which returns the data type FILE *, the function fopen_s returns the data type errno_t.

In the code you posted, you pass the address of the variable fPointer to the function fopen_s, so that it will write to that variable. This is correct. However, afterwards, you explicitly assign the return value of the function fopen_s (which is of type errno_t) to the variable fPointer, thereby overwriting what was previously written to that variable by the function fopen_s. This should not be done, as the data type errno_t has a different meaning than the data type FILE *.

Also, as a general rule, you should always check whether a file was successfully opened before you use a FILE *.

Therefore, you should change your code to something like the following:

#include <stdlib.h>

int main()
{
    FILE* fPointer;
    errno_t err;

    err = fopen_s(&fPointer,"‪C:\\asd.txt","w");
    if ( err == 0 )
    {
        fprintf(fPointer, "If ı can read this then ı can create for loop");
        fclose(fPointer);
    }
    else
    {
        fprintf( stderr, "Error opening file!\n" );
    }

    return 0;
}

Upvotes: 3

Eraklon
Eraklon

Reputation: 4288

fopen_s return value is an error number and you overwrite your file pointer with that which you should not do.

Upvotes: 4

Related Questions