Writing synchronously to a file opened with FILE_F

2019-07-06 04:01发布

问题:

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 synchronous 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.

回答1:

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.



回答2:

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.