简体   繁体   English

我可以允许多个程序同时从同一个文件中读取吗?

[英]Can I allow multiple programs to read from the same file at the same time?

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 . 由于我的开发环境是Windows 7, 因此这个问题表明它可能是启用读取共享的问题 However, all of the answers in that thread rely on CreateFile , whereas I'm dealing with legacy code that was written with stdio.h. 但是,该线程中的所有答案都依赖于CreateFile ,而我正在处理使用stdio.h编写的遗留代码。

Is there a way I can have several programs concurrently read from a file using the fopen class of functions? 有没有办法可以使用fopen类函数从文件中同时读取多个程序?

If you can change the fopen routine then try to replace fopen calls with _fsopen , for shared reading/writing. 如果你可以改变fopen例程,那么尝试用_fsopen替换fopen调用,以进行共享读/写。 _fsopen is mscrt-specific. _fsopen是特定于mscrt的。

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. 如果您可以使用CreateFile ,并且不想重写所有遗留代码以进行读/写,您还可以尝试将FILE *与winapi文件句柄相关联。 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. 使用_open_osfhandleCreateFile返回的文件句柄中获取文件描述符,然后使用_fdopen从该文件描述符中获取FILE *

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM