c++datetimewinapiwindows-8.1c++builder-xe7

Last write FILETIME always returning current time


I need to compare a file's last modified time to a date time stored in a database. I initially looked at this question to get started.

I am currently getting the FILETIME for the last write of the file, converting it to a SYSTEMTIME. Then I use that SYSTEMTIME to create a TDateTime object that I can use for my comparison. However, the FileModifiedDT variable, is always coming out to be the current time, despite the file having been modified previously.

FILETIME lastWriteTime;

String * FileNamePtr = new String( FileName );

GetFileTime( FileNamePtr, NULL, NULL, &lastWriteTime );

SYSTEMTIME systemTime;
FileTimeToSystemTime( &lastWriteTime, &systemTime );

TDateTime * FileModifiedDT = new TDateTime( systemTime.wYear, systemTime.wMonth,
                                            systemTime.wDay, systemTime.wHour,
                                            systemTime.wMinute, systemTime.wSecond,
                                            systemTime.wMilliseconds );

Am I missusing GetFileTime in some way? Is there a better way I should go about this?


Solution

  • The error is

    String * FileNamePtr = new String( FileName );
    GetFileTime( FileNamePtr, NULL, NULL, &lastWriteTime );
    

    According to the documentation, the first argument has to be a file handle created by CreateFile and nothing else.

    Thus you need something like this:

    HANDLE fileHandle = CreateFile(
      FileName, //LPCTSTR
      GENERIC_READ,
      FILE_SHARE_READ,
      NULL,
      OPEN_EXISTING,
      FILE_ATTRIBUTE_NORMAL,
      NULL
    );
    
    if ( fileHandle != INVALID_HANDLE )
    {
        GetFileTime( fileHandle, NULL, NULL, &lastWriteTime );
        CloseHandle( fileHandle );
    }
    else
    {
        // error, do something else...
    }