I/O 异步访问

15 篇文章 0 订阅
11 篇文章 0 订阅
#include <iostream>
#include <string>
#include <windows.h>
using namespace std;

HANDLE g_readEvent, g_writeEvent;

int main()
{
	g_readEvent = CreateEvent( NULL, FALSE, FALSE, NULL );
	g_writeEvent = CreateEvent( NULL, FALSE, FALSE, NULL );

	HANDLE hFile1 = CreateFile( TEXT("1.TXT"),
		GENERIC_READ | GENERIC_WRITE,
		0, // must be opened with exclusive-access
		NULL, // no security attributes
		OPEN_EXISTING, // must use OPEN_EXISTING
		FILE_FLAG_OVERLAPPED, // overlapped I/O
		NULL // htemplate must be NULL for comm devices
		);

	if( INVALID_HANDLE_VALUE == hFile1 )
	{
		cout << " open File failed !" << endl;
	}
	else
	{
		/* read process */
		BYTE bBuffer[100] = { 0 };
		OVERLAPPED o = { 0 };
		o.Offset = 0;
		o.hEvent = g_readEvent;

		BOOL bReadDone = ReadFile( hFile1, bBuffer, 100, NULL, &o );

		/* write process */
		BYTE bWriteBuffer[10] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
		OVERLAPPED oWrite = { 0 };
		oWrite.Offset = 10;
		oWrite.hEvent = g_writeEvent;

		WriteFile( hFile1, bWriteBuffer, _countof( bWriteBuffer ), NULL, &oWrite );

		HANDLE h[2];
		h[0] = o.hEvent;
		h[1] = oWrite.hEvent;

		while(1)
		{
			DWORD dwStatus = WaitForMultipleObjects( 2, h, FALSE, INFINITE );
			switch ( dwStatus - WAIT_OBJECT_0 )
			{
			case  0:
				cout << " Read complete " << endl;
				break;
			case 1:
				cout << " Write complete " << endl;
				break;
			default:
				break;
			}
		}

	}




	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值