Domanda

I am trying to debug a program that manipulates a file. For example, I set the file-pointer to offset 4 (using a base of 0), but it seems to be starting at offset 5 instead.

To try to figure out what is happening, I want to put in a line to print out the current file pointer (I’m not using an IDE for this little project, just Notepad2 and the command-line). Unfortunately there does not seem to be a Windows API function to retrieve the current file pointer, only one to set it.

I’m recall being able to find the current file pointer in Pascal (in DOS), but how can the current file pointer be determined in C++ in Windows?

È stato utile?

Soluzione

Unlike most functions, that provide both a getter and setter (in the read-write sense), there is indeed no GetFilePointer or GetFilePointerEx.

However the value can be retrieved by calling SetFilePointer(Ex). The two SetFilePointer functions return the the return/output from SetFilePointer, but you have to make sure to specify an offset of 0, and FILE_CURRENT as the mode. That way, it moves 0 bytes from where it is, then returns (I can’t vouch for whether or not it wastes CPU cycles and RAM to perform the zero-move, but I would think they have optimized to not do so).

Yes, it is inconsistent and confusing (and redundant and poorly designed), but you can wrap it in your own GetFilePointer(Ex) function:

DWORD    GetFilePointer   (HANDLE hFile) {
    return SetFilePointer(hFile, 0, NULL, FILE_CURRENT);
}


LONGLONG GetFilePointerEx (HANDLE hFile) {
    LARGE_INTEGER liOfs={0};
    LARGE_INTEGER liNew={0};
    SetFilePointerEx(hFile, liOfs, &liNew, FILE_CURRENT);
    return liNew.QuadPart;
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top