C – fopen_s cannot write to a file made by CreateFile

Home / Uncategorized / C – fopen_s cannot write to a file made by CreateFile

I have a main.c function and a subfunction that is called within it. In the subfunction I have used CreateFile to make a file. I then use CloseHandle to close the handle to that file. When I use fopen_s after that (within the subfunction) it works with both read and write modes. But if I use fopen_s in the main function afterwards, I can only open with read access, or else I get error code 13 – permission denied. The parameters of my CreateFile function are as follows:hAppend = CreateFile(centralDataFilepath, // open central data file
FILE_APPEND_DATA, // open for writing
FILE_SHARE_READ|FILE_SHARE_WRITE, // allow multiple readers
NULL, // no security
OPEN_ALWAYS, // open or create
NULL); // no attr. template

And I use fopen_s as follows:FILE *f2;
errno_t errorCode3 = 0;
errorCode3 = fopen_s(&f2, centralDataFilepath, "a+");

I don’t actually know if CreateFile has anything to do with this, it seems like the permission of the file changes after I exit the subfunction? I need to be able to write to this file, would anyone know why I am getting this permission denied error, and how to fix it?

As described here:

Files that are opened by fopen_s and _wfopen_s are not sharable.

Function failed because it can’t lock file for writing. You need to use _fsopen instead. Try this:f2 = _fsopen(centralDataFilepath, "a+", _SH_DENYNO);
Read more

Leave a Reply

Your email address will not be published. Required fields are marked *