Search code examples
cvisual-studiofopenc11tr24731

What is unsafe about fopen?


When using fopen(), Microsoft Visual Studio prints:

warning C4996: 'fopen' was declared deprecated`

The reason given is:

This function or variable may be unsafe. Consider using fopen_s instead.

What is unsafe about fopen() that's more safe in fopen_s()?

How can fopen() be used in a safe way (if possible)?


Solution

  • The Microsoft CRT implements the secure library enhancements described in C11 Annex K. Which is normative but not mandatory. fopen_s() is described in section K.3.5.2.1. Also covered by rule FIO06-C of the CERT institute.

    At issue is that fopen() dates from simpler times when programmers could still assume that their program was the only one manipulating files. An assumption that has never really been true. It does not have a way to describe how access to the file by other processes is limited, CRT implementations traditionally opened the file without denying any access. Non-standard alternatives have been used to fix this problem, like _fsopen().

    This has consequences if the file is opened for writing, another process can also open the file for writing and the file content will be hopelessly corrupted. If the file is opened for reading while another process is writing to it then the view of the file content is unpredictable.

    fopen_s() solves these problems by denying all access if the file is opened for writing and only allowing read access when the file is opened for reading.