views:

426

answers:

4

How do I get the file size and date stamp of a file on Windows in C++, given its path?

+3  A: 

GetFileSize/GetFileSizeEx and GetFileInformationByHandleEx with FileBasicInfo can be used to retrieved this information.

Both functions take a handle, so you need to use CreateFile on the path prior to calling these functions.

// Error handling removed for brevity
HANDLE hFile = CreateFile(path, GENERIC_READ, FILE_SHARE_READ,
                 NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);

LARGE_INTEGER fileSize;
GetFileSizeEx(hFile, &fileSize);

FILE_BASIC_INFO fileInfo);
GetFileInformationByHandle(hFile, FileBasicInfo, fileInfo, sizeof(fileInfo));

// fileInfo.CreationTime is when file was created.
Michael
+3  A: 

You could also use POSIX stat, if you were looking for portability. Windows still supports its use.

Matthew Iselin
Good idea, although it seems unavailable in WinCE. Upvote!
Qwertie
+3  A: 

To append the other answer, you call GetFileTime to get just the file times. This API also requries a handle and I think is easier than GetFileInformationByHandle API. BTW the GetFileInformationByHandleEx is only supported in VISTA and above.

Shane Powell
I swore this api existed, but my search for GetFileTimes (note the s) came up with nothing. Good catch.
Michael
My answer was more meant to be a add-on to yours anyway. I see yours as a more complete answer to the question, which is why I voted yours up.
Shane Powell
+2  A: 

You can use FindFirstFile() to get them both at once, without having to open it (which is required by GetFileSize() and GetInformationByHandle()). It's a bit laborious, however, so a little wrapper is helpful

bool get_file_information(LPCTSTR path, WIN32_FIND_DATA* data)
{
  HANDLE h = FindFirstFile(path, &data);
  if(INVALID_HANDLE_VALUE != h) {
    return false;
  } else {
    FindClose(h);
    return true;
  }
}

Then the file size is available in the nFileSizeHigh and nFileSizeLow members of WIN32_FIND_DATA, and the timestamps are available in the ftCreationTime, ftLastAccessTime and ftLastWriteTime members.

DannyT
There are three errors in your example, and it should be noted how to decode the time stamp: call FileTimeToSystemTime. Anyway, thanks.
Qwertie
Oops. Writing in haste! Fixed now. :-)
DannyT