Can't open file with CreateFile function

Hi. I'm using windows xp, and I tried to open the pfirewall.log file in C:\WINDOWS directory, but it fails every time, GetLastError() returns 32. The message reads "The process cannot access the file because it is being used by another process"
I use this code to open the file
 
HANDLE hFile = CreateFile(szPath, GENERIC_READ, FILE_SHARE_READ, 0, OPEN_EXISTING, 0, 0);


Why can windows notepad open this file without a problem but my program can't?
Last edited on
Files in windows can be opened with varying permissions. And also with sharing restrictions.

For example... if you want exclusive access to a file for reading, you can open with reading permissions, but you can omit the FILE_SHARE_READ flag. This will have 2 effects:

1) Your attempt to open will fail if the file is already open for reading somewhere else (you can't obtain exclusive access to it)

and

2) If your attempt succeeds, then no other program can open the file with reading permissions for as long as you have it open (you have exclusive access).



In your case, you are hitting scenario #1. You are attempting to open the file with exclusive access (likely write access), but some other program already has it open with write permission.

So... don't request exclusive access. Allow all types of sharing:

1
2
// I'm removing the wretched hungarian notation because BLECH
HANDLE file = CreateFile(path, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, 0, OPEN_EXISTING, 0, 0);


by specifying all 3 FILE_SHARE flags, you're effectively saying "I don't care what other programs want to do with this file while I have it open".


Note that this could still fail, though. If whatever program that has it open does not SHARE_READ, then you simply will be unable to open it. Though judging from the fact that Notepad is able to open it... I doubt that will be a problem.
Thanks Disch now I was able to open the file
Topic archived. No new replies allowed.