I need to read several lines from file simultaneously, i.e. asynchronously. Lines in file are of the same size.
For instance, I need to read the second and the fourth lines of file to separate variables or to an array.
I'm more used to c#'s async/await and all these OVERLAPPED
things are a bit difficult for understanding to me.
Using msdn examples, I achieved this, it just reads the data from the file as a one string (is that even asynchronous reading?):
BOOL ReadFromFileAsync(PCTSTR path)
{
HANDLE hFile = CreateFile(path, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING,
FILE_FLAG_OVERLAPPED | FILE_FLAG_NO_BUFFERING, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
_tprintf_s(TEXT("INVALID_HANDLE_VALUE\n"));
return FALSE;
}
BOOL bResult;
BYTE bReadBuf[2048];
OVERLAPPED oRead = { 0 };
oRead.hEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
bResult = ReadFile(hFile, bReadBuf, _countof(bReadBuf), NULL, &oRead);
if (!bResult && GetLastError() != ERROR_IO_PENDING)
{
_tprintf_s(TEXT("ERROR io pending"));
CloseHandle(hFile);
return FALSE;
}
// perform some stuff asynchronously
_tprintf_s(TEXT("HEY\n"));
HANDLE hEvents[2];
hEvents[0] = oRead.hEvent;
hEvents[1] = oRead.hEvent;
DWORD dwWaitRes = WaitForMultipleObjects(_countof(hEvents), hEvents, FALSE, INFINITE);
switch (dwWaitRes - WAIT_OBJECT_0)
{
case 0: // reading finished
_tprintf_s(TEXT("String that was read from file: "));
for (int i = 0; i < oRead.InternalHigh; ++i)
_tprintf_s(TEXT("%c"), bReadBuf[i]);
_tprintf_s(TEXT("\n"));
break;
default:
_tprintf_s(TEXT("Nooo"));
}
CloseHandle(hFile);
return TRUE;
}
Could you help me with reading two lines from file asynchronously?
Should I use SetFilePointer
for that to move through the lines?
When you open a file with the
FILE_FLAG_OVERLAPPED
flag and then use anOVERLAPPED
structure withReadFile()
, use theOVERLAPPED.Offset
andOVERLAPPED.OffsetHigh
fields to specify the byte offset where reading should start from. Also, you must use a separateOVERLAPPED
instance for eachReadFile()
if you run them simultaneously. This is clearly stated in the documentation:As your lines are the same length, you can easily calculate the offsets of the second and fourth lines and then issue two asynchronous
ReadFile()
calls for those offsets, and then wait for the two operations to complete as needed.On a side note, you really should not be using
FILE_FLAG_NO_BUFFERING
unless you REALLY know what you are doing:Try something more like this instead:
Alternatively: