问题
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