Skip to content

Instantly share code, notes, and snippets.

@ianfun
Created May 9, 2022 07:36
Show Gist options
  • Save ianfun/89f269c11bf516597a69809fcb77c295 to your computer and use it in GitHub Desktop.
Save ianfun/89f269c11bf516597a69809fcb77c295 to your computer and use it in GitHub Desktop.
ReadFileEx example - async read whole file
#include <windows.h>
#include <stdio.h>
constexpr auto DWORD_size(){
return sizeof(DWORD);
}
#define BUFZ 101
char buf[BUFZ];
HANDLE hstdout = GetStdHandle(STD_OUTPUT_HANDLE);
VOID LpoverlappedCompletionRoutine(
DWORD dwErrorCode,
DWORD dwNumberOfBytesTransfered,
LPOVERLAPPED lpOverlapped){
// printf("dwErrorCode=%d, dwNumberOfBytesTransfered=%d\n", dwErrorCode, dwNumberOfBytesTransfered);
if (dwErrorCode | dwNumberOfBytesTransfered<=0){
// maybe EOF reached?
}else{
constexpr auto size = DWORD_size();
if constexpr (size==4)
*((__int64*)&lpOverlapped->Offset) += dwNumberOfBytesTransfered;
else if constexpr (size==8)
*((__int128*)&lpOverlapped->Offset) += dwNumberOfBytesTransfered;
else {
abort();
}
WriteConsoleA(hstdout, buf, dwNumberOfBytesTransfered, NULL, NULL);
if (ReadFileEx(lpOverlapped->hEvent, buf, sizeof(buf)-1, lpOverlapped, LpoverlappedCompletionRoutine)==FALSE){
puts("ReadFileEx failed 2!");
}
SleepEx(100, TRUE);
}
}
INT main(VOID)
{
if (hstdout==NULL){
puts("GetStdHandle failed!!");
return 1;
}
OVERLAPPED ol {};
ol.hEvent = CreateFileA(__FILE__,
GENERIC_READ,
FILE_SHARE_READ,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED,
NULL);
if (ol.hEvent==NULL){
puts("CreateFileA failed!!");
return 2;
}
if (ReadFileEx(ol.hEvent, buf, sizeof(buf)-1, &ol, LpoverlappedCompletionRoutine)==FALSE){
puts("ReadFileEx failed!!");
return 3;
}
SleepEx(INFINITE, TRUE); // need alertable wait to call async procedure, such as WSAaccept and SleepEx
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment