Why can't I use fopen?

前端 未结 6 1316
北荒
北荒 2020-12-08 15:06

In the mold of a previous question I asked about the so-called safe library deprecations, I find myself similarly bemused as to why fopen() should be deprecated

6条回答
  •  情歌与酒
    2020-12-08 15:41

    The fopen_s() function has been added by Microsoft to the C runtime with the following fundamental differences from fopen():

    • if the file is opened for writing ("w" or "a" specified in the mode) then the file is opened for exclusive (non-shared) access (if the platform supports it).
    • if the "u" specifier is used in the mode argument with the "w" or "a" specifiers, then by the time the file is closed, it will have system default permissions for others users to access the file (which may be no access if that's the system default).
    • if the "u" specified is not used in those cases, then when the file is closed (or before) the permissions for the file will be set such that other users will not have access to the file.

    Essentially it means that files the application writes are protected from other users by default.

    They did not do this to fopen() due to the likelyhood that existing code would break.

    Microsoft has chosen to deprecate fopen() to encourage developers for Windows to make conscious decisions about whether the files their applications use will have loose permissions or not.

    Jonathan Leffler's answer provides the proposed standardization language for fopen_s(). I added this answer hoping to make clear the rationale.

提交回复
热议问题