4

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 stackoverflow articles that answer that question)

Edit: Question was closed as "opinion based" (even though there is only one answer and I don't see much opinion in that). I'll try to rephrase a bit: It would be nice if someone could show how/where to find the documentation by Microsoft (who deprecated the function) that explains why it was deprecated.

Deduplicator
  • 41,806
  • 6
  • 61
  • 104
Sebastian
  • 1,733
  • 11
  • 16
  • 3
    Possible duplicate of [fopen deprecated warning](https://stackoverflow.com/questions/14386/fopen-deprecated-warning) – Jean-François Fabre Sep 17 '17 at 16:00
  • 2
    @Jean-FrançoisFabre I do not see the answer to this question in any of the answers on your proposed duplicate link. –  Sep 17 '17 at 16:13
  • @hvd; I thought that "Anyway, if you aren't interested in using the secure version of their calls (like fopen_s), you need to place a definition of _CRT_SECURE_NO_DEPRECATE before your included header files" answered. – Jean-François Fabre Sep 17 '17 at 16:22
  • 2
    @Jean-FrançoisFabre That's how to suppress the warning, which is what this question explicitly did not ask. It doesn't address the rationale, nor how to use `fopen` to avoid whatever pitfalls `fopen_s` prevents. –  Sep 17 '17 at 18:26
  • `fopen` is only deprecated by Microsoft, not by the C standard. – n. 'pronouns' m. 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

1 Answers1

8

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
  • 873,011
  • 131
  • 1,552
  • 2,371