根据创建日期对文件进行排序?

时间:2015-05-05 03:31:27

标签: c++ visual-studio-2013 mfc

第一个问题解决了。文件完美排列。

for (int i = 0; i < allFiles.GetSize(); i++)
{
    box1.AddString(allFiles[i]);
}

vector<file> files;

vector<tstring> vec;
vec.insert(vec.begin(), &allFiles[0], &allFiles[allFiles.GetSize() - 1] + 1);

transform(vec.begin(), vec.end(),back_inserter(files),[](wstring const &fname)
{
    WIN32_FIND_DATA d;
    HANDLE h = FindFirstFile(fname.c_str(), &d);
    FindClose(h);
    return d;
}

);

sort(files.begin(), files.end());
CStringArray sortFiles;
files.insert(files.begin(), &sortFiles[0], &sortFiles[sortFiles.GetSize() - 1] + 1);

现在问题是我如何在CStringArray中保存排序文件。 Last Statement显示错误见评论?

1 个答案:

答案 0 :(得分:1)

根据创建日期或上次写入日期对文件进行排序的简单方法是将文件存储到映射中,其中Key是日期,值是文件名。地图将为您排序..我的代码示例如下..

BOOL GetLastWriteTime(FILETIME ftWrite, LPWSTR lpszString, DWORD dwSize)
{
     DWORD dwRet;
     SYSTEMTIME st, stLocal;
    // Convert the last-write time to local time.
    FileTimeToSystemTime(&ftWrite, &st);
    SystemTimeToTzSpecificLocalTime(NULL, &st, &stLocal);

    // Build a string showing the date and time.
    dwRet = StringCchPrintf(lpszString, dwSize, 
        TEXT("%02d%02d%d%02d%02d%02d%04d"),
        stLocal.wMonth, stLocal.wDay, stLocal.wYear,
        stLocal.wHour, stLocal.wMinute, stLocal.wSecond, stLocal.wMilliseconds);

    if( S_OK == dwRet )
        return TRUE;
    else return FALSE;
}


int _tmain(int argc, _TCHAR* argv[])
{
    std::map<wstring, wstring> first;

     wstring directory = L"D:\\SourceCode\\FilesTemp\\*";
     std::wstring name;
     WCHAR szBuf[MAX_PATH];
     WIN32_FIND_DATA d;
     HANDLE hFindFile   = FindFirstFile ( directory.c_str(), &d );

     if (hFindFile == INVALID_HANDLE_VALUE) 
    {
        DWORD dwLastError = ::GetLastError();

        if( dwLastError != ERROR_NO_MORE_FILES &&
            dwLastError != ERROR_FILE_NOT_FOUND)
        {
            return FALSE;
        }

        // No files found
        return TRUE;
    }
     do
     {
         if( d.cFileName[0] &&  _tcscmp( d.cFileName, _T( "." )) != 0 &&_tcscmp( d.cFileName, _T( ".." )) != 0 )
         {
             name = d.cFileName;
             if(GetLastWriteTime( d.ftLastWriteTime, szBuf, MAX_PATH ))
             {
                _tprintf(TEXT("Last write time is: %s\n"), szBuf);
                first[szBuf] = name;
             }
         }
     }while (FindNextFile ( hFindFile, &d ));

    return 0;
}