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?
If you can change the
fopenroutine then try to replacefopencalls with_fsopen, for shared reading/writing._fsopenis 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 aFILE *with a winapi file handle. Use_open_osfhandleto get a file descriptor from a file handle returned byCreateFile, then use_fdopento get aFILE *from that file descriptor.