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

4
如何在C++中按修改时间排序文件? std::sort函数需要一个比较函数。它以向量作为参数。我想根据修改时间对文件进行排序。是否已经有可用的比较函数或API可以用来实现这一点?

1
Windows?Linux?Mac Os X?获取文件修改日期是一个特定于操作系统的任务。为了实现跨平台性,请查看Boost。 - dario_ramos
寻找Linux解决方案 - user839917
1个回答

2

是的,你可以使用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的开销。


2
我已经用安卓手机验证过了,它运行良好。 - hismart
1
警告:如果在排序过程中由外部进程更改了mtimes,则此操作可能会导致崩溃。最好先制作时间列表,然后对其进行排序,这样既快又安全。 - SF.
很好的观点;我会更新答案。 - dario_ramos

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接