Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C4996, fopen deprecated: Why? (NOT: How to suppress) [closed]

When using fopen(), Microsoft Visual Studio prints

warning C4996: 'fopen' was declared deprecated`

As reason is given:

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

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

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

I don't want to know how to suppress the warning - there are enough Stack Overflow articles that answer that question.

like image 451
Sebastian Avatar asked Jan 29 '23 14:01

Sebastian


1 Answers

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.

like image 174
Hans Passant Avatar answered Feb 01 '23 10:02

Hans Passant