Skip to content

Instantly share code, notes, and snippets.

@ianfun
Created July 11, 2022 14:06
Show Gist options
  • Save ianfun/360bc4074ddefdc3d64697c8b574a132 to your computer and use it in GitHub Desktop.
Save ianfun/360bc4074ddefdc3d64697c8b574a132 to your computer and use it in GitHub Desktop.
Rename File on Disk using SetFileInformationByHandle | Win32 API
#define _UNICODE
#define UNICODE
#include <windows.h>
#ifdef __cplusplus
#include <cstdio>
#else
#include <stdio.h>
#endif
int wmain(int argc, const WCHAR** argv)
{
if (argc < 2)
{
wprintf_s(L"Usage: %ws [src path] [dst path]\n", argv[0]);
return 1;
}
HANDLE hFile = CreateFile(argv[1],
DELETE,
0,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
puts("error: CreateFile failed");
return GetLastError();
}
DWORD dstLen = lstrlenW(argv[2]);
DWORD infoSize = sizeof(FILE_RENAME_INFO) + (dstLen + 1) * 2;
FILE_RENAME_INFO* info = (FILE_RENAME_INFO*)malloc(infoSize);
info->ReplaceIfExists = TRUE;
info->RootDirectory = NULL;
info->FileNameLength = dstLen;
memcpy(info->FileName, argv[2], (dstLen + 1)*2);
BOOL res = SetFileInformationByHandle(hFile, FileRenameInfo, info, infoSize);
free(info);
if(res==FALSE){
puts("error: SetFileInformationByHandle failed");
return GetLastError();
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment