fopen for writing but not exclusive

微笑、不失礼 提交于 2021-01-24 09:23:30

问题


I want to use fopen("file", "w") to open a file for writing but not exclusive. I.e. I want to have another process read the file while it is still open.

Note that I have a flush after every line so I won't miss anything. Writing will be idle at the time the other process reads from the file.

The documentation does not mention exclusive but experimenting shows that it is exclusive.

Is there a way?


回答1:


Shared access on files is an OS-specific feature. fopen is too generic and does not provide that kind of control. You would need to use something more specific. If you are using a microsoft platform (assuming since you tagged for VS 2015) you can use _fsopen or _wfsopen - they have a third parameter to specify the shared access.

_fsopen("file", "w", _SH_DENYWR);

this will open the file for writing and allow others to read from it (but not write to it).

The argument shflag is a constant expression consisting of one of the following manifest constants, defined in Share.h.

  • Term Definition
  • _SH_COMPAT Sets Compatibility mode for 16-bit applications.
  • _SH_DENYNO Permits read and write access.
  • _SH_DENYRD Denies read access to the file.
  • _SH_DENYRW Denies read and write access to the file.
  • _SH_DENYWR Denies write access to the file.

Other OS/platforms may support some variation of fsopen too.



来源:https://stackoverflow.com/questions/54631617/fopen-for-writing-but-not-exclusive

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!