Why can't I use fopen?

JamieH picture JamieH · May 25, 2009 · Viewed 21.1k times · Source

In the mold of a previous question I asked about the so-called safe library deprecations, I find myself similarly bemused as to why fopen() should be deprecated.

The function takes two C strings, and returns a FILE* ptr, or NULL on failure. Where are the thread-safety problems / string overrun problems? Or is it something else?

Thanks in advance

Answer

paxdiablo picture paxdiablo · May 25, 2009

You can use fopen(). Seriously, don't take any notice of Microsoft here, they're doing programmers a real disservice by deviating from the ISO standards . They seem to think that people writing code are somehow brain-dead and don't know how to check parameters before calling library functions.

If someone isn't willing to learn the intricacies of C programming, they really have no business doing it. They should move on to a safer language.

This appears to be just another attempt at vendor lock-in by Microsoft of developers (although they're not the only ones who try it, so I'm not specifically berating them). I usually add:

#define _CRT_SECURE_NO_WARNINGS

(or the "-D" variant on the command line) to most of my projects to ensure I'm not bothered by the compiler when writing perfectly valid, legal C code.

Microsoft has provided extra functionality in the fopen_s() function (file encodings, for one) as well as changing how things are returned. This may make it better for Windows programmers but makes the code inherently unportable.

If you're only ever going to code for Windows, by all means use it. I myself prefer the ability to compile and run my code anywhere (with as little change as possible).


As of C11, these safe functions are now a part of the standard, though optional. Look into Annex K for full details.