我在获取目录的最新文件时遇到问题。
除非该文件夹中只有一个文件,否则我的代码工作正常。
我正在使用 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/