如何在C++中按修改时间排序文件?
std::sort
函数需要一个比较函数。它以向量作为参数。我想根据修改时间对文件进行排序。是否已经有可用的比较函数或API可以用来实现这一点?是的,你可以使用std::sort
并告诉它使用一个自定义比较对象,像这样:
#include <algorithm>
std::vector<string> vFileNames;
FileNameModificationDateComparator myComparatorObject;
std::sort (vFileNames.begin(), vFileNames.end(), myComparatorObject);
FileNameModificationDateComparator
类的代码(可以使用更短的名称):
#include <sys/stat.h>
#include <unistd.h>
#include <time.h>
/*
* TODO: This class is OS-specific; you might want to use Pointer-to-Implementation
* Idiom to hide the OS dependency from clients
*/
struct FileNameModificationDateComparator{
//Returns true if and only if lhs < rhs
bool operator() (const std::string& lhs, const std::string& rhs){
struct stat attribLhs;
struct stat attribRhs; //File attribute structs
stat( lhs.c_str(), &attribLhs);
stat( rhs.c_str(), &attribRhs); //Get file stats
return attribLhs.st_mtime < attribRhs.st_mtime; //Compare last modification dates
}
};
这里是stat结构的定义,以防万一。
警告:我没有检查过这段代码。
更新:根据评论,如果在排序期间有外部进程修改文件,则此解决方案可能失败。最安全的方法是首先stat
所有文件,然后对它们进行排序。有关此特定情况的详细信息,请参见此问题。
更新2:我很久以前回答了这个问题。现在,如果您的C++代码需要与文件系统交互并需要在多个操作系统上工作,我强烈建议使用Boost,以避免所有跨系统的头疼问题。请记住,您可以“修剪”Boost,以仅获取应用程序所需的库;无需捆绑整套库。这大大降低了使用Boost的开销。