简体   繁体   中英

To check SetFilePointerEx, ReadFile or WriteFile for success do I need to check lpNewFilePointer, lpNumberOfBytesRead and lpNumberOfBytesWritten?

I'm somewhat puzzled by SetFilePointerEx, ReadFile and WriteFile APIs. Say, if I want to move file pointer to a new position, is it sufficient to do:

if(SetFilePointerEx(hFile, liPtr, NULL, FILE_BEGIN))
{
    //Success, moved file pointer to liPtr position
}

Or, do I need to check the value returned in lpNewFilePointer too, as such?

LARGE_INTEGER liSetTo = {0};
if(SetFilePointerEx(hFile, liPtr, &liSetTo, FILE_BEGIN) &&
    liPtr.QuadPart == liSetTo.QuadPart)
{
    //Success
}

The same applies to ReadFile and WriteFile. For instance:

if(WriteFile(hFile, buffer, numberBytesToWrite, NULL, NULL))
{
    //Success writing numberBytesToWrite into file
}

Or do I need to do this to make sure that all my data was written successfully:

DWORD numberBytesWritten = 0;
if(WriteFile(hFile, buffer, numberBytesToWrite, &numberBytesWritten, NULL) &&
    numberBytesWritten == numberBytesToWrite)
{
    //Success writing numberBytesToWrite into file
}

In other words, what's the point to have those return sizes and offsets? I mean, if I want it to write 1024 bytes into a file, can it just write 1000 instead. :) If it doesn't write all the data that I requested it to, wouldn't it constitute an error, or FALSE to be returned from the API?

Anyway, I'd appreciate if someone could clarify.

For SetFilePointerEx , you should only check it's return value. It contains whether the operation was a SUCCESS.

For a synchronous ReadFile / WriteFile , if it returns false, then the operation has completely failed (no bytes read/written at all). If it returns true, then you should check lpNumberOfBytesRead / lpNumberOfBytesWritten , as it can be lower then the number you specified. For example, for read, if EOF reached, then you'll get a short read. For write, if disk becomes full during write, you may get a short write.

There could be other various reasons for short read/write, so your code should handle these cases.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM