用CFileFind类遍历一个文件夹下的文件,发现它并不是按照windows标准的按文件名排序方式排序的,比如说1.txt,2.txt,3.txt,4.txt,5.txt,...80.txt,81.txt,...100.txt,101.txt.....在windows下应该是这样的顺序,但是让CFileFind类遍历后却成了1.txt。10.txt,100.txt,2.txt
#include <algorithm>
#include <vector>
CFileFind finder;
std::vector<CString> fileList;
// 加入文件到fileList中
BOOL bHaveFiles = finder.FindFile("*.*");
while (bHaveFiles)
{
bHaveFiles = finder.FindNextFile();
fileList.push_back(finder.GetFileName());
}
// 写一个全局的谓词函数
// 升序排列
bool SortbyNumASC(const CString& x, const CString& y)
{
int nLeft, nRight;
nLeft = atoi(x.Left(x.ReverseFind('.')).GetBuffer(0));
nRight = atoi(y.Left(y.ReverseFind('.')).GetBuffer(0));
return nLeft<nRight;
}
// 降序排列
bool SortbyNumDESC(const CString& x, const CString& y)
{
int nLeft, nRight;
nLeft = atoi(x.Left(x.ReverseFind('.')).GetBuffer(0));
nRight = atoi(y.Left(y.ReverseFind('.')).GetBuffer(0));
return nLeft>nRight;
}
// 排序
/// 由大到小排
sort(fileList.begin(), fileList.end(), SortbyNumDESC);
/// 由小到大排
sort(fileList.begin(), fileList.end(), SortbyNumASC);
原文地址:http://bbs.youkuaiyun.com/topics/220078959