c ++中按修改时间对文件进行排序 [英] file sort in c++ by modification time
本文介绍了c ++中按修改时间对文件进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在C ++中按修改时间对文件排序?
How to sort a file by modification time in C++?
std::sort
需要比较功能.
它以向量为参数.我想根据修改对文件进行排序.
我已经可以使用比较功能或API来实现此目的了吗?
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?
推荐答案
是的,您可以使用std::sort
并告诉它使用自定义比较对象,如下所示:
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);
FileNameModificationDateComparator
类的代码(可以使用简短的名称):
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
}
};
此处的统计结构定义,以防万一.
警告:我没有检查此代码
这篇关于c ++中按修改时间对文件进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文