// Overlapped.cpp : 定义控制台应用程序的入口点。
#include "stdafx.h"
#include <windows.h>#include <iostream>using namespace std;VOID CALLBACK CompletionRoutine( _In_ DWORD ErrorCode, _In_ DWORD ReturnLength, _Inout_ LPOVERLAPPED Overlapped);HANDLE __FileHandle = NULL;char __BufferData[20] = {0}; int main(){ BOOL IsOk = FALSE; OVERLAPPED Overlapped = { 0 }; __FileHandle = CreateFile(L"ReadMe.txt", GENERIC_ALL, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL|FILE_FLAG_OVERLAPPED, NULL); if (__FileHandle == INVALID_HANDLE_VALUE) { int LastError = GetLastError(); goto Exit; } //通知IO有异步IO和Overlapped的设置,读四个字节每次 //不用等待是因为没有创建事件当然不用搞 //OverLapped这里的作用是利用Overlapped->Offset 往下加字节设置位置读取字节 IsOk = ReadFileEx(__FileHandle, __BufferData, 4,&Overlapped, (LPOVERLAPPED_COMPLETION_ROUTINE)CompletionRoutine); if (IsOk == FALSE) { int LastError = GetLastError(); if (LastError == ERROR_IO_PENDING) { } }Exit: SleepEx(0,TRUE);//只有为TRUE时候,等待完成历程返回时退出 if (__FileHandle != NULL) { CloseHandle(__FileHandle); __FileHandle = NULL; } printf("Input AnyKey To Exit\r\n"); getchar(); return 0;}VOID CALLBACK CompletionRoutine( _In_ DWORD ErrorCode, _In_ DWORD ReturnLength, _Inout_ LPOVERLAPPED Overlapped){ if (ErrorCode == ERROR_SUCCESS) { int i = 0; for (i = 0; i < ReturnLength; i++) { printf("%c", __BufferData[i]); }Overlapped->Offset += ReturnLength;//
ReadFileEx(__FileHandle, __BufferData, 4, Overlapped, (LPOVERLAPPED_COMPLETION_ROUTINE)CompletionRoutine); } else if (ErrorCode==ERROR_HANDLE_EOF) { //数据完成 printf("\r\n"); GetFileSize } else { }}