I have an application that reads a set of data files and performs some model computations. The program does not need to modify the data files themselves, so I'm currently opening them with the read-only flag as shown below:
FILE* file;
if(_wfopen_s(&file, fname.c_str(), L"r") == 0)
...
I would like to have several instances of my program running at the same time, using the same set of data, but performing different computations on the data. None of my programs need to modify the data files. As the data files are very large, I can't make separate copies of the data to use with each program.
I assumed that because I'm opening the files with read-only permissions, two programs could be reading from the same file at the same time. Instead, I get various errors along the lines of "the file could not be open because it is being used by another process".
As my development environment is Windows 7, this question suggests it might be a matter of enabling read sharing. However, all of the answers in that thread rely on CreateFile, whereas I'm dealing with legacy code that was written with stdio.h.
Is there a way I can have several programs concurrently read from a file using the fopen class of functions?
It's okay to ACCESS the file from two different programs, as long as you don't try to MODIFY it from two different programs.
The process of opening (and if necessary creating) the file is atomic, so it will never happen that one process will create the file but the other process will open it. Note: this is specific to Windows, other operating systems have different behaviour.
no, generally it is not safe to do this! you need to obtain an exclusive write lock for each process -- that implies that all the other processes will have to wait while one process is writing to the file.. the more I/O intensive processes you have, the longer the wait time.
Risk Assessment. Simultaneously opening a file multiple times can result in unexpected errors and nonportable behavior.
If you can change the fopen
routine then try to replace fopen
calls with _fsopen
, for shared reading/writing. _fsopen
is mscrt-specific.
If you can use CreateFile
, and don't want to re-write all the legacy code for read/write, you can also try associating a FILE *
with a winapi file handle. Use _open_osfhandle
to get a file descriptor from a file handle returned by CreateFile
, then use _fdopen
to get a FILE *
from that file descriptor.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With