问题
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.
回答1:
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.
来源:https://stackoverflow.com/questions/46266053/c4996-fopen-deprecated-why-not-how-to-suppress