同步写入使用 FILE_FLAG_OVERLAPPED 打开的文件
我已经使用
HANDLE handle=
CreateFileW(
fileName, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING,
FILE_FLAG_OVERLAPPED, NULL);
文件句柄打开了一个文件,然后将其用于异步读取操作:
ReadFile(handle, buffer, 1, NULL, &overlapped);
这有效。但是,我现在想做一个同步写入。 WriteFile
文件指出
如果 hFile 使用 FILE_FLAG_OVERLAPPED 打开,则以下条件生效:
• lpOverlapped 参数必须指向有效且唯一的OVERLAPPED 结构,否则函数可能会错误地报告写入操作已完成。
当省略 lpOverlapepd
参数时,GetLastError()
将返回 ERROR_INVALID_PARAMETER
。打开两个句柄(一个用于读取,一个用于写入)也不起作用,因为第二个句柄会产生 ERROR_ACCESS_DENIED
错误。
如何打开文件进行异步读取和同步写入?我不想不必要地增加代码复杂性。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
同步写入可以通过为写入操作创建手动重置事件、写入文件(使用写入操作的重叠结构中的事件)然后立即等待该事件来实现。
根据异步读取是否需要与写入异步,您可能需要确保使用兼容的等待,以便可以调用读取完成例程,否则将发生读取并且数据将存储在缓冲区中,但你无法处理它。
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.
打开两个句柄,一个用于异步读取,另一个用于同步写入,只需确保设置文件共享属性
(FILE_SHARE_READ|FILE_SHARE_WRITE)
。还没有测试过。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.