fopen 用于写作但不排他

fopen for writing but not exclusive

我想用fopen("file", "w")打开一个文件进行写入但不是独占。 IE。我想让另一个进程在文件仍然打开时读取它。

请注意,我在每一行之后都进行了冲洗,这样我就不会错过任何内容。在其他进程从文件中读取时,写入将处于空闲状态。

文档中没有提到独占,但实验表明它是独占的。

有办法吗?

文件的共享访问是 OS 特定的功能。 fopen 过于通用,不提供那种控制。你需要使用更具体的东西。如果您使用的是 Microsoft 平台(假设您标记为 VS 2015),您可以使用 _fsopen or _wfsopen - 他们有第三个参数来指定共享访问。

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

这将打开文件进行写入并允许其他人从中读取(但不能写入)。

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.

其他 OS/platforms 也可能支持 fsopen 的某些变体。