Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I use fopen?

Tags:

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

like image 310
JamieH Avatar asked May 25 '09 12:05

JamieH


People also ask

Why is fopen not working?

ERRORS. The fopen() function will fail if: [EACCES] Search permission is denied on a component of the path prefix, or the file exists and the permissions specified by mode are denied, or the file does not exist and write permission is denied for the parent directory of the file to be created.

When fopen () is not able to open a file it returns?

Explanation: fopen() returns NULL if it is not able to open the given file due to any of the reasons like file not present, inappropriate permissions, etc.

Can I use fopen in C++?

The fopen() function in C++ opens a specified file in a certain mode.


1 Answers

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.

like image 110
paxdiablo Avatar answered Sep 30 '22 15:09

paxdiablo