用c++;按修改时间 如何在C++中修改文件的排序?
用c++;按修改时间 如何在C++中修改文件的排序?,c++,linux,sorting,std,C++,Linux,Sorting,Std,std::sort需要一个比较函数。 它以vector作为参数。我想根据修改对文件进行排序。 是否已经有一个比较函数或API可供我使用以实现此目的?是的,您可以使用std::sort并告诉它使用自定义比较对象,如下所示: #include <algorithm> std::vector<string> vFileNames; FileNameModificationDateComparator myComparatorObject; std::sort (vFileNa
std::sort
需要一个比较函数。它以vector作为参数。我想根据修改对文件进行排序。
是否已经有一个比较函数或API可供我使用以实现此目的?是的,您可以使用
std::sort
并告诉它使用自定义比较对象,如下所示:
#include <algorithm>
std::vector<string> vFileNames;
FileNameModificationDateComparator myComparatorObject;
std::sort (vFileNames.begin(), vFileNames.end(), myComparatorObject);
,以防万一
警告:我没有检查此代码Windows?Linux?MacOSX?获取文件修改日期是一项特定于操作系统的任务。对于跨平台性,请查看linuxI中的BoostLooking解决方案,该解决方案已通过android手机验证。它很好用
#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
}
};