开发者

Writing synchronously to a file opened with FILE_FLAG_OVERLAPPED

I have opened a file using

HANDLE handle= 
    CreateFileW(
        fileName, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 
        FILE_FLAG_OVERLAPPED, NULL);

The file handle is then used for asynchronous read operations:

ReadFile(handle, buffer, 1, NULL, &overlapped);

This works. However, I want to do a sy开发者_开发技巧nchronous write now. WriteFile documentation states that

If hFile was opened with FILE_FLAG_OVERLAPPED, the following conditions are in effect:

• The lpOverlapped parameter must point to a valid and unique OVERLAPPED structure, otherwise the function can incorrectly report that the write operation is complete.

When the lpOverlapepd parameter is omitted, ERROR_INVALID_PARAMETER is returned by GetLastError(). Opening two handles, one for reading and one for writing does also not work since the second handle produces a ERROR_ACCESS_DENIED error.

How can I open the file for asynchronous reads and synchronous writes? I don't want to increase code complexity unnecessarily.


Synchronous writes can be achieved by creating a manual reset event for the write operation, writing to the file (using the event in the overlapped structure for your write operation) and then immediately waiting for the event.

Depending on whether your asynchronous read needs to be asynchronous with your write, you may need to make sure you use a compatible wait so that your read completion routine can be called otherwise the read will take place and the data will be stored in the buffer but you cannot process it.


Open two handles, one for async read the other for sync write, just make sure that you set the file share attributes (FILE_SHARE_READ|FILE_SHARE_WRITE). Haven't tested it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜