简体   繁体   English

win32 C / C ++从“锁定”文件中读取数据

[英]win32 C/C++ read data from a “locked” file

Any idea how to read data from a file that is locked by another process? 知道如何从另一个进程锁定的文件中读取数据吗?

When I try fopen() or CreateFile() or OpenFile() I get sharing violation. 当我尝试fopen()或CreateFile()或OpenFile()时,出现共享冲突。

Yet if I go to command prompt and do a "c:> more blah.h" I can see the file. 但是,如果我转到命令提示符并执行“ c:> more blah.h”,则可以看到该文件。 So "more" somehow can read the file. 因此,“更多”可以以某种方式读取文件。 Any idea how it accomplishes that? 知道它是如何实现的吗?

Thanks! 谢谢!

I am trying to open it as "read-only". 我试图将其打开为“只读”。 ie. 即。 "r" in fopen() and GENERIC_READ, FILE_SHARE_READ in create file fopen()中的“ r”和创建文件中的GENERIC_READ,FILE_SHARE_READ

Clearly the file is not locked from reading, otherwise the more command could not have worked. 显然,文件没有被锁定以防止读取,否则more命令无法正常工作。 So the process did specify read sharing when it created the file. 因此,该过程在创建文件时确实指定了读取共享。 The mistake is only specifying FILE_SHARE_READ in your own attempt to open the file. 错误仅是您自己尝试打开文件时指定了FILE_SHARE_READ。 That denies write sharing. 那否认了写共享。 That cannot work, the process has already acquired write access to the file, you cannot deny it. 那行不通,该进程已经获得了对该文件的写访问权,您不能拒绝它。 Instead you'll be denied access with the sharing violation. 相反,您将因为共享冲突而被拒绝访问。 You must also specify FILE_SHARE_WRITE to gain access to the file. 您还必须指定FILE_SHARE_WRITE才能访问该文件。

That will fix your problem. 那将解决您的问题。 Only other wrinkle is that you'll be reading from a file that's being written to. 唯一的麻烦是您将从正在写入的文件中读取。 So data in the file changes entirely unpredictably. 因此,文件中的数据完全无法预测。

一种方法是将文件复制到新的临时文件,然后读取该文件。

fopen is deprecated and msdn recommends fopen_s but sharing isnt enabled for that . 不建议使用fopen,msdn建议使用fopen_s,但没有为此启用共享。

Files opened by fopen_s and _wfopen_s are not sharable. 由fopen_s和_wfopen_s打开的文件不可共享。 If you require that a file be sharable, use _fsopen, _wfsopen with the appropriate sharing mode constant (for example, _SH_DENYNO for read/write sharing). 如果您要求文件可共享,请使用_fsopen,_wfsopen和适当的共享模式常量(例如,_SH_DENYNO用于读/写共享)。

use _fsopen to open the file and enable a flag to share ( _SH_DENYNO ) to give sharing access. 使用_fsopen打开文件并启用共享标记(_SH_DENYNO)以提供共享访问权限。

fsopen fsopen

请阅读此内容-http://msdn.microsoft.com/zh-cn/library/windows/desktop/aa363858(v=vs.85).aspx当您说“访问冲突”时,您的意思是Win32 0xc000005错误, 或者是其他东西?

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

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