How to modify a file date and time to current date and time in C++ Win32 API

1 Answer

0 votes
#include <Windows.h> 

int CALLBACK WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) {
    // Get the current system time
    SYSTEMTIME systemTime;
    GetSystemTime(&systemTime);

    // Convert SYSTEMTIME to FILETIME
    FILETIME fileTime;
    SystemTimeToFileTime(&systemTime, &fileTime);

    // Open the file with write attributes access
    HANDLE hFile = CreateFile(
        L"d:\\data.txt",
        FILE_WRITE_ATTRIBUTES,
        FILE_SHARE_READ | FILE_SHARE_WRITE,
        NULL,
        OPEN_EXISTING,
        FILE_ATTRIBUTE_NORMAL,
        NULL
    );

    if (hFile == INVALID_HANDLE_VALUE) {
        MessageBoxA(0, "Failed to open file", "Error", MB_OK);
        return 1;
    }

    // Set the file time to the current time
    if (!SetFileTime(hFile, NULL, NULL, &fileTime)) {
        MessageBoxA(0, "Failed to set file time", "Error", MB_OK);
        CloseHandle(hFile);
        return 1;
    }

    CloseHandle(hFile);

    return 0;
}

// File is set to current date and time: data.txt 20 07/12/2024 12:14

/*
run:

check the file date and time on your hard disk drive

*/

 



answered Dec 7, 2024 by avibootz
edited Dec 7, 2024 by avibootz
...