2

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.

Yet if I go to command prompt and do a "c:> more blah.h" I can see the file. So "more" somehow can read the file. Any idea how it accomplishes that?

Thanks!

  • Are you opening the file as read-only or as read/write? "more" opens as read-only. – Charles Burns Jan 03 '13 at 03:51
  • Access violation is not necessarily for locked file. Some actual code will be useful. – Rohan Jan 03 '13 at 04:05
  • Sorry meant sharing violation. I am trying to open it as "read-only". ie. "r" in fopen() and GENERIC_READ, FILE_SHARE_READ in create file. –  Jan 03 '13 at 05:32
  • I guess one way to do it is copy the file to a new temporary file? –  Jan 03 '13 at 05:34

4 Answers4

4

I am trying to open it as "read-only". ie. "r" in fopen() and GENERIC_READ, FILE_SHARE_READ in create file

Clearly the file is not locked from reading, otherwise the more command could not have worked. 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. 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.

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.

Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
  • You are probably right! Will give it a try and update. I don't really mind about the data changing as I know for sure that data only get appended. So my app will work kind of like "tail -f". Thanks! –  Jan 03 '13 at 20:49
1

One way is to copy the file to a new temporary one and read that.

1

fopen is deprecated and msdn recommends fopen_s but sharing isnt enabled for that .

Files opened by fopen_s and _wfopen_s are not sharable. 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).

use _fsopen to open the file and enable a flag to share ( _SH_DENYNO ) to give sharing access.

fsopen

0

Please read this - http://msdn.microsoft.com/en-us/library/windows/desktop/aa363858(v=vs.85).aspx When you say , "access violations", do you mean a Win32 0xc000005 error, or something else?

OldProgrammer
  • 12,050
  • 4
  • 24
  • 45