SetFileSize function
Namespace: Windows::Storage
Header: fileapi.h
Syntax
BOOL SetFileSize(
HANDLE hFile,
LARGE_INTEGER liSize
);
Parameters
| Parameter | Type | Description |
|---|---|---|
| hFile | HANDLE | Handle to the file. The handle must have GENERIC_WRITE access. |
| liSize | LARGE_INTEGER | New size for the file, in bytes. |
Return value
Returns nonzero if successful; otherwise, 0. Use GetLastError for extended error information.
Remarks
The function changes the physical size of the file. If the new size is smaller, the file is truncated. If larger, the file is extended and the contents of the new area are undefined.
This function is a wrapper around SetEndOfFile and SetFilePointerEx. When possible, prefer the newer API calls for better compatibility.
Example
#include <windows.h>
#include <stdio.h>
int main()
{
HANDLE h = CreateFileW(L"example.txt",
GENERIC_WRITE,
0,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
NULL);
if (h == INVALID_HANDLE_VALUE) {
wprintf(L"CreateFile failed: %lu\\n", GetLastError());
return 1;
}
LARGE_INTEGER newSize;
newSize.QuadPart = 1024 * 1024; // 1 MB
if (!SetFileSize(h, newSize)) {
wprintf(L"SetFileSize failed: %lu\\n", GetLastError());
CloseHandle(h);
return 1;
}
wprintf(L"File size set to 1 MB.\\n");
CloseHandle(h);
return 0;
}