file sort in c++ by modification time
How to sort a file by modification time in C++?
std::sort
needs a comparison function.
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
UPDATE: Per comment, this solution can fail if there is an external process modifying the files while sort takes place. It's safer to stat
all the files first, and then sort them. See this question for details on this particular scenario.
UPDATE 2: I answered this a very long time ago. Nowadays, if your C++ code needs to interact with the file system and needs to work on multiple OSes, I would strongly advise using Boost to avoid all cross-system headaches. Remember that you can "trim" Boost to only get the libraries your app needs; there is no need to bundle the whole suite of libraries. This reduces the overhead of using Boost considerably.
精彩评论