file sort in c++ by modification time

南笙酒味 提交于 2019-12-22 11:12:40

问题


How to sort a file by modification time in C++?

std::sort needs a comparison function.
It takes vector as the arguments. I want to sort files based on modification. Is there already a comparison function or API available that I can use to achieve this?


回答1:


Yes, you can use std::sort and tell it to use a custom comparison object, like this:

#include <algorithm>

std::vector<string> vFileNames;
FileNameModificationDateComparator myComparatorObject;
std::sort (vFileNames.begin(), vFileNames.end(), myComparatorObject);

The code for the FileNameModificationDateComparator class (feel free to use a shorter name):

#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, just in case.

Warning: I didn't check this code



来源:https://stackoverflow.com/questions/7337651/file-sort-in-c-by-modification-time

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!