c++中文件按修改时间排序

file sort in c++ by modification time

本文关键字:时间 排序 修改 中文 文件 c++      更新时间:2023-10-16

如何在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 struct的定义,以防万一。

警告: I didn't check this code

UPDATE:根据注释,如果排序发生时存在修改文件的外部进程,则此解决方案可能会失败。更安全的做法是先对所有文件进行stat处理,然后再进行排序。有关此特定场景的详细信息,请参阅此问题。

UPDATE 2:我很久以前就回答过这个问题了。现在,如果您的c++代码需要与文件系统交互,并且需要在多个操作系统上工作,我强烈建议使用Boost来避免所有跨系统的麻烦。记住,你可以"修剪"。Boost只获取应用程序所需的库;没有必要将整个库套件捆绑在一起。这大大减少了使用Boost的开销。