Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

CreateFile Fails - Second Execution On Same File

5 views
Skip to first unread message

Le Chaud Lapin

unread,
Nov 16, 2009, 11:57:41 PM11/16/09
to
Hi All,

See code below. Why does the second call fail?

Do I misunderstand the MSDN documentation?

http://msdn.microsoft.com/en-us/library/aa363858(VS.85).aspx

TIA,

-Le Chaud Lapin-

#include <windows.h>

int main (int argc, char *argv[], char *envp[])
{
// Please make sure the following file exists before running:
TCHAR szFilePath[] = "C:\\FOO.DOCX";

HANDLE h1 = CreateFile (
szFilePath,
GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
NULL);

HANDLE h2 = CreateFile (
szFilePath,
GENERIC_READ,
FILE_SHARE_READ,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
NULL);

DWORD dwError = GetLastError();

return 0;
}

Uwe Sieber

unread,
Nov 17, 2009, 3:07:07 AM11/17/09
to

Because it's opened for writing and the second
call don't want to share write. With
"FILE_SHARE_READ | FILE_SHARE_WRITE" it will
work.

Uwe

David Lowndes

unread,
Nov 17, 2009, 3:47:59 AM11/17/09
to
>See code below. Why does the second call fail?

Because the first instance is opened for reading and writing, the
second one needs to allow the same sharing. i.e. it should be:

HANDLE h2 = CreateFile (
szFilePath,
GENERIC_READ,
FILE_SHARE_READ | FILE_SHARE_WRITE,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
NULL);

You can test these usages of CreateFile using multiple instances of my
CFTest utility:
http://jddesign.co.uk/products/freeware/freeware_programs.htm#CFTest

Dave

Uwe Sieber

unread,
Nov 17, 2009, 6:20:03 AM11/17/09
to
David Lowndes wrote:
>
> You can test these usages of CreateFile using multiple instances of my
> CFTest utility:
> http://jddesign.co.uk/products/freeware/freeware_programs.htm#CFTest

Here is mine :-)
http://www.uwe-sieber.de/files/CreateFileTest.zip


Uwe

0 new messages