when trying to write file fprintf does not work

3

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.

c
io
asked on Stack Overflow Feb 22, 2020 by Naber

3 Answers

4

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

answered on Stack Overflow Feb 22, 2020 by Eraklon
3

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;
}
answered on Stack Overflow Feb 22, 2020 by Andreas Wenzel • edited Feb 22, 2020 by Andreas Wenzel
0

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

answered on Stack Overflow Feb 22, 2020 by Jahangir • edited Feb 22, 2020 by chux - Reinstate Monica

User contributions licensed under CC BY-SA 3.0