Erik
Erik

Reputation: 43

C : fopen_s() returns NULL if it works, so I cant close it with flose() and it also dont work togehter with fwrite()

Normally I would use fopen but with Visual Studio you have to use the secure variant fopen_s. But because fopen_s returns a NULL pointer if the action was successful, I cannot use the fclose() function to close the connection to the file. fclose(filePointer) is not possible because it is a NULL pointer. If I want to use functions like fwrite() or fread() that doesn't work either.

My Problem is when I use fwrite(str, 1, sizeof(str), filePointer) -> "filePointer could be 0". Of cause its 0 because I get "0" if fopen_s(filePointer) works well.

Unfortunately, I can't find any examples of the security variants anywhere, because everyone uses the "normal" ones. I know that I can switch off the safety function, but I don't really want to do that, because safety is actually something good :D

Upvotes: 2

Views: 584

Answers (1)

paxdiablo
paxdiablo

Reputation: 881633

An example is right there on Microsoft's doco page (abridged here):

FILE *stream;
errno_t err = fopen_s(&stream, "crt_fopen_s.c", "r");
if (err == 0) {
    fclose(stream);
}

The first argument to fopen_s is a pointer to the variable that will receive the file handle, so it's that variable that you use to do whatever you need to do to the file (which is just closing it im my example above).


Note that these functions are not safe, though they may be safer than the originals. They check for specific NULL values but there are plenty of unsafe pointers that aren't NULL(a).

It's always been my view that good code design makes these checks unnecessary, though I realise some may disagree(b). Probably one of the first lines I put in my C programs is:

#define _CRT_SECURE_NO_WARNINGS

so as not to have to put up with what I consider to be the Microsoft nanny state.


(a) Such as (void*)42, for example.

(b) They are, of course, wrong. 😀

Upvotes: 7

Related Questions