从目录中选择上次修改的文件

Fah*_*.ag 6 c++ directory

我需要知道,如何在给定目录中选择上次修改/创建的文件.

我目前有一个名为XML的目录,里面有很多XML文件.但我想只选择最后修改过的文件.

Tib*_*ibi 4

我使用以下函数列出文件夹内的所有项目。它将所有文件写入字符串向量中,但您可以更改它。

bool ListContents (vector<string>& dest, string dir, string filter, bool recursively)
{
    WIN32_FIND_DATAA ffd;
    HANDLE hFind = INVALID_HANDLE_VALUE;
    DWORD dwError = 0; 

    // Prepare string
    if (dir.back() != '\\') dir += "\\";

    // Safety check
    if (dir.length() >= MAX_PATH) {
        Error("Cannot open folder %s: path too long", dir.c_str());
        return false;
    }

    // First entry in directory
    hFind = FindFirstFileA((dir + filter).c_str(), &ffd);

    if (hFind == INVALID_HANDLE_VALUE) {
        Error("Cannot open folder in folder %s: error accessing first entry.", dir.c_str());
        return false;
    }

    // List files in directory
    do {
        // Ignore . and .. folders, they cause stack overflow
        if (strcmp(ffd.cFileName, ".") == 0) continue;
        if (strcmp(ffd.cFileName, "..") == 0) continue;

        // Is directory?
        if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
        {
            // Go inside recursively
            if (recursively) 
                ListContents(dest, dir + ffd.cFileName, filter, recursively, content_type);
        }

        // Add file to our list
        else dest.push_back(dir + ffd.cFileName);

    } while (FindNextFileA(hFind, &ffd));

    // Get last error
    dwError = GetLastError();
    if (dwError != ERROR_NO_MORE_FILES) {
        Error("Error reading file list in folder %s.", dir.c_str());
        return false;
    }

    return true;
}
Run Code Online (Sandbox Code Playgroud)

(不要忘记包含 windows.h)

您要做的就是调整它以找到最新的文件。ffd 结构体(WIN32_FIND_DATAA 数据类型)包含 ftCreationTime、ftLastAccessTime 和 ftLastWriteTime,您可以使用它们来查找最新的文件。这些成员是 FILETIME 结构,您可以在此处找到文档:http://msdn.microsoft.com/en-us/library/windows/desktop/ms724284%28v=vs.85%29.aspx