c++ - CFileFind 不考虑目录的第一个文件

标签 c++ mfc cfilefind

我在获取目录的最新文件时遇到问题。 除非该文件夹中只有一个文件,否则我的代码工作正常。 我正在使用 CFileFind 类来实现这一切。我查看了 Microsoft 文档,它说 .GetFileName 只能在 FindNextFile 之后调用。如果有人有解决方案,我将非常感激。 这是我的代码:

std::string getLatestFile(std::string directory, const std::string& extension) {
        FILETIME mostRecent = { 0, 0 };
        FILETIME curDate;
        std::string name;
        CFileFind finder;
        if (!CheckIfDirectory(directory))
            return "";
        ensureProperTermination(directory);//this just makes sure that the path is "\\" terminated
        if (extension[0] == '.')
            finder.FindFile((directory + "*" + extension).c_str());
        else
            finder.FindFile((directory + "*." + extension).c_str());

        while (finder.FindNextFile())
        {
            finder.GetCreationTime(&curDate);

            if (CompareFileTime(&curDate, &mostRecent) > 0)
            {
                mostRecent = curDate;
                name = finder.GetFileName().GetString();
            }
        }
        return directory + name;
    }

最佳答案

这样做:

void GetAllFilesNames(const CString& sMask, CStringArray& files)
{
    CFileFind finder;
    BOOL bWorking = finder.FindFile(sMask);
    while (bWorking)
    {
        bWorking = finder.FindNextFile();

        // skip . and .. files
        if (!finder.IsDots())
        {
            files.Add(finder.GetFileName());
        }
    }

}

所以调用看起来像这样:

CStringArray Files;
GetAllFilesNames(_T("C:\\Test\\*.txt"), Files);

在您的情况下,它看起来像这样:

CString GetMostRecent(const CString& sMask)
{    
    CFileFind finder;
    BOOL bWorking = finder.FindFile(sMask);
    CTime dt;
    CString sMostRecent;
    while (bWorking)
    {
        bWorking = finder.FindNextFile();

        // skip . and .. files
        if (!finder.IsDots())
        {
            CTime lw;
            finder.GetLastWriteTime(lw);

            if (lw > dt)
            {
                dt = lw;
                sMostRecent = finder.GetFileName();
            }

        }
    }

    return sMostRecent;

关于c++ - CFileFind 不考虑目录的第一个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51533814/

相关文章:

c++ - 如何避免文件扩展名超过三个字符的 CFileFind 误报?

c++ - OpenCV 不释放相机

c++ - 编译 boost 信号2的问题

数组的 C++ 构造函数初始值设定项

c++ - 这个 C++ 转换代码在做什么?

c++ - 如何在 MDI MFC C++ Windows 应用程序中动态更改 CFormView WIDTH 或 HEIGHT?

c++ - MFC/WIN32/C++ : How to dispatch messages while doing a computationally intensive operation?

c++ - 带有 Aero 主题(阴影)的窗口定位 - 0,0 处的窗口隐藏了一些边框