6

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)?

Mehdi Charife
  • 722
  • 1
  • 7
  • 22
Sebastian
  • 1,839
  • 12
  • 16
  • 3
    `fopen` is only deprecated by Microsoft, not by the C standard. – n. m. could be an AI Sep 17 '17 at 20:12
  • 1
    See this : https://stackoverflow.com/questions/19396116/how-can-fopen-s-be-more-safe-than-fopen – Garf365 Oct 27 '17 at 09:11
  • What's unsafe about `fopen()`? Read **all** of this before you follow Microsoft's self-serving "deprecation": [**Field Experience With Annex K — Bounds Checking Interfaces**](https://www.open-std.org/jtc1/sc22/wg14/www/docs/n1967.htm#impementations): "Microsoft Visual Studio implements an early version of the APIs. However, the implementation is incomplete and conforms neither to C11 nor to the original TR 24731-1. ... As a result of the numerous deviations from the specification the Microsoft implementation cannot be considered conforming or portable." – Andrew Henle Apr 25 '23 at 01:11

1 Answers1

10

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.

Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536