问题
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 inShare.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