Number of bytes read by synchronous ReadFile
Assume I have 1Mb file, file pointer is at the beginning of the file. I call synchronous ReadFile:
ReadFile(Handle, Buffer, 1024, Result, nil);
the call is succesful, no error occured. Is it possible that Result value (number of bytes read) is less than 1024 (number of bytes to read)?
I think that is impossible for disk files, I am not sure about other resources that can be accessed by ReadFile. Should I take the above scenario into account while writing a general code that can work with different resources?
To avo开发者_Python百科id philosophical speculations I can reformulate the question as follows:
Synchronous ReadFile was executed without error and a number of bytes read is less than a number of to read. Can I be sure that EOF is reached?
In your given scenario, it does seem that for disk files it would be impossible to receive less bytes read than the requested number of bytes.
However, writing general code that can work with different resources, you should not rely on always receiving the requested number of bytes in the situation where position + bytes requested is less than the total number of bytes to be transferred.
For example Readfile can return 0 bytes read on a successful call when the other end of a named pipe called WriteFile with 0 bytes to write...
MSDN seems to say only the following w.r.t. when ReadFile returns less than the requested number of bytes for a file (i.e. not a socket, pipe, etc.): https://msdn.microsoft.com/en-us/library/windows/desktop/aa365467(v=vs.85).aspx
When a synchronous read operation reaches the end of a file, ReadFile returns TRUE and sets *lpNumberOfBytesRead to zero.
I can't find any proof or disproof that ReadFile will not read a smaller chunk of the file and return the size of that chunk when the file contains no less than the originally requested number of bytes. Thus I am writing code which checks how many bytes ReadFile returns, and calls ReadFile again (in a loop) so long as the total number of bytes returned is less than the requested number of bytes, unless ReadFile returns 0 bytes which means EOF according to MSDN.
A practical implication:
- call GetFileSizeEx and allocate a buffer of size reported by that function
- call ReadFile requesting to read the whole buffer at once
- the programmer can't rely that ReadFile will not read a smaller chunk reporting that number of bytes read
精彩评论