Search code examples
c++winapisystemtime

C++ System Time returning the same wrong value


I want to retrieve the last write date on a file. I have written this code for it, but it returns me 52428 in values like "Year" all the time

int LastErrorCode;
LPCSTR Path = "C:/Users/Username/Desktop/Picture.PNG";
WIN32_FIND_DATA Information;

if(!FindFirstFile(Path, &Information))
{
    int LastErrorCode = GetLastError();
    cout << "FIND FIRST FILE FAILED" << endl;
    cout << LastErrorCode << endl;
}


SYSTEMTIME MyTime;
FILETIME MyFileTime = Information.ftLastWriteTime;


if(!FileTimeToSystemTime(&MyFileTime, &MyTime))
{
    LastErrorCode = GetLastError();
    cout << "FILE TIME TO SYSTEM TIME FAILED" << endl;
    cout << LastErrorCode << endl;
}


cout << MyTime.wYear << endl;

Solution

  • The hex value for 52428 is 0xCCCC, which seems to indicate it has not been initialized. The function call is probably failing. Check the return codes from FindFirstFile and FileTimeToSystemTime (and then call GetLastError after a failure to find the error code).

    Edit Based on the edits to the OP, the FindFirstFile call is likely the one that is failing. The return value is a handle (not a zero/non-zero result). The code should assign the result to a variable of type HANDLE and then compare against INVALID_HANDLE_VALUE.

    Note too that after a successful call to FindFirstFile, the code should have a corresponding call to FindClose with the handle to avoid leaking resources.