Domanda

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;
È stato utile?

Soluzione

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.

Altri suggerimenti

Please check the documentation of this function! It tells you the following:

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Try to check if the return value is nonzero, if it's not, try calling getlasterror and print that error message on the console and provide this information.

In the past, I have used WIN32_FILE_ATTRIBUTE_DATA instead of WIN32_FIND_DATA. Then to get the file's information, I use GetFileAttributesEx. An example is below:

string strFile = "c:\\myfile.txt";

WIN32_FILE_ATTRIBUTE_DATA    fileInfo;
// Get the attributes structure of the file
if ( GetFileAttributesEx(strFile, 0, &fileInfo) )
{
    SYSTEMTIME        stSystemTime;
    // Convert the last access time to SYSTEMTIME structure: 
    if ( FileTimeToSystemTime(&fileInfo.ftLastAccessTime, &stSystemTime) )
    {
        printf("Year = %d,  Month = %d,  Day = %d,  Hour = %d,  Minute = %d\n", stSystemTime.wYear, stSystemTime.wMonth, stSystemTime.wDay, stSystemTime.wHour, stSystemTime.wMinute);
    }

Shouldn't you use backslashes '\' in file path? Provided that this would correct your file path, the FindFirstFile API call might possibly succeed and would get you the time you needed.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top