C++(18):获取windows下文件的创建/修改/访问时间

#include 
#include 
//----------- Error Handling Function -------------------
void error(LPSTR lpszFunction)
{
    CHAR szBuf[80];
    DWORD dw = GetLastError();

	snprintf(szBuf, sizeof(szBuf), "%s failed: GetLastError returned %u\n",lpszFunction, dw);

    MessageBox(NULL, szBuf, "Error", MB_OK);
    ExitProcess(dw);
}
//--------------------------------------------------------

BOOL GetFileTime(HANDLE hFile, LPSTR lpszCreationTime, LPSTR lpszLastAccessTime, LPSTR lpszLastWriteTime)
{
    FILETIME ftCreate, ftAccess, ftWrite;
    SYSTEMTIME stUTC1, stLocal1, stUTC2, stLocal2, stUTC3, stLocal3;

    // -------->获取 FileTime
    if (!GetFileTime(hFile, &ftCreate, &ftAccess, &ftWrite)){
        error((LPSTR)"GetFileTime()");
        return FALSE;
    }
    //---------> 转换: FileTime --> LocalTime
    FileTimeToSystemTime(&ftCreate, &stUTC1);
    FileTimeToSystemTime(&ftAccess, &stUTC2);
    FileTimeToSystemTime(&ftWrite, &stUTC3);

    SystemTimeToTzSpecificLocalTime(NULL, &stUTC1, &stLocal1);
    SystemTimeToTzSpecificLocalTime(NULL, &stUTC2, &stLocal2);
    SystemTimeToTzSpecificLocalTime(NULL, &stUTC3, &stLocal3);

    // ---------> Show the  date and time.
    wsprintf(lpszCreationTime, "创建时间:\t%02d/%02d/%d  %02d:%02d",
        stLocal1.wDay, stLocal1.wMonth, stLocal1.wYear,
        stLocal1.wHour, stLocal1.wMinute);
    wsprintf(lpszLastAccessTime, "最后访问时间:\t%02d/%02d/%d  %02d:%02d",
        stLocal2.wDay, stLocal2.wMonth, stLocal2.wYear,
        stLocal2.wHour, stLocal2.wMinute);
    wsprintf(lpszLastWriteTime, "最后修改时间:\t%02d/%02d/%d  %02d:%02d",
        stLocal3.wDay, stLocal3.wMonth, stLocal3.wYear,
        stLocal3.wHour, stLocal3.wMinute);
    return TRUE;
}
//----------------------------------------------------------------
int main()
{

    HANDLE hFile;
    TCHAR szCreationTime[30], szLastAccessTime[30], szLastWriteTime[30];
    hFile = CreateFile("D:/test.txt", 0, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
    GetFileTime(hFile, szCreationTime, szLastAccessTime, szLastWriteTime);
    if (hFile == INVALID_HANDLE_VALUE){
        error("GetLastWriteTime()");
        return 0;
    }
    printf("%s\n%s\n%s\n", szCreationTime, szLastAccessTime, szLastWriteTime);
    CloseHandle(hFile);
    system("pause");

    return 0;
}

调用就在main函数中,需要访问的文件就是 CreateFile() 函数的第一个参数

 

需要强调一下,vs中编译的时候需要在项目属性中,将字符编码改为 "多字节字符集",默认的是unicode

C++(18):获取windows下文件的创建/修改/访问时间_第1张图片

 

 

参考文章:https://www.cnblogs.com/autumoonchina/p/5852265.html

你可能感兴趣的:(C++)