SetFilePointer
Namespace: FileAPI
Header: Windows.h
Library: Kernel32.lib
DLL: Kernel32.dll
Synopsis
DWORD WINAPI SetFilePointer(
HANDLE hFile,
LONG lDistanceToMove,
PLONG lpDistanceToMoveHigh,
DWORD dwMoveMethod
);
Parameters
- hFile – A handle to the file. The handle must have been created with
GENERIC_READ
orGENERIC_WRITE
. - lDistanceToMove – The low-order 32 bits of the distance to move the file pointer.
- lpDistanceToMoveHigh – Pointer to the high-order 32 bits of the distance to move. Set to
NULL
if not needed. - dwMoveMethod – Starting point for the move. One of:
FILE_BEGIN
– Beginning of the file.FILE_CURRENT
– Current file pointer.FILE_END
– End of the file.
Return Value
If the function succeeds, the return value is the low-order DWORD of the new file pointer. On failure, the return value is INVALID_SET_FILE_POINTER
(0xFFFFFFFF
) and you can call GetLastError
for extended error information.
Remarks
SetFilePointer
moves the file pointer associated with a file handle. It can be used to seek forward or backward in a file, or to obtain the current file pointer position by passing a zero distance and FILE_CURRENT
.
Example
#include <windows.h>
#include <stdio.h>
int main(void)
{
HANDLE hFile = CreateFileA(
"example.bin",
GENERIC_READ | GENERIC_WRITE,
0,
NULL,
OPEN_ALWAYS,
FILE_ATTRIBUTE_NORMAL,
NULL);
if (hFile == INVALID_HANDLE_VALUE) {
printf("CreateFile failed (error %lu)\\n", GetLastError());
return 1;
}
// Move to the end of the file
LONG high = 0;
DWORD pos = SetFilePointer(hFile, 0, &high, FILE_END);
if (pos == INVALID_SET_FILE_POINTER && GetLastError() != NO_ERROR) {
printf("SetFilePointer failed (error %lu)\\n", GetLastError());
CloseHandle(hFile);
return 1;
}
printf("Current file size: %llu bytes\\n",
((unsigned long long)high << 32) | pos);
// Write some data at the end
const char *text = "Hello, SetFilePointer!\\n";
DWORD written;
WriteFile(hFile, text, (DWORD)strlen(text), &written, NULL);
printf("Wrote %lu bytes.\\n", written);
CloseHandle(hFile);
return 0;
}