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

标签 c++ linux sorting std

如何在 C++ 中按修改时间对文件进行排序?

std::sort 需要一个比较函数。
它以 vector 作为参数。我想根据修改对文件进行排序。 是否已经有可用的比较函数或 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 definition here ,以防万一。

警告:我没有检查这段代码

更新:根据评论,如果在进行排序时有外部进程修改文件,则此解决方案可能会失败。先对所有文件进行stat,再进行排序比较安全。参见 this question有关此特定场景的详细信息。

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

关于c++ - 按修改时间在c++中排序文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7337651/

相关文章:

php - 以简单的 PHP 形式显示来自两个或多个查询的不同数据

python - 如何制作一个始终在 Linux 终端中运行的脚本?

java - 我如何按字母顺序对数组列表进行排序

Java 字符串数组

c++ - 有人知道 `cimg::exception_mode() = 0;` 是做什么的吗?

c++ - 从文件读取导致无限循环的问题

c++ - 彼此组成的类

linux - 如何在linux上将安装的gdb添加到系统路径

java - 如何高效获取数百万未排序 float 的排名?

c++ - 从函数返回一个包含另一个对象的对象