c++中文件按修改时间排序
file sort in c++ by modification time
如何在c++中按修改时间对文件进行排序?
std::sort
需要一个比较函数
它以向量作为参数。我想根据修改对文件进行排序。是否已经有一个比较函数或API可用,我可以使用它来实现这一点?
是的,您可以使用std::sort
并告诉它使用自定义比较对象,如:
#include <algorithm>
std::vector<string> vFileNames;
FileNameModificationDateComparator myComparatorObject;
std::sort (vFileNames.begin(), vFileNames.end(), myComparatorObject);
FileNameModificationDateComparator
类的代码(可以随意使用更短的名称):
#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的定义,以防万一。
警告: I didn't check this code
UPDATE:根据注释,如果排序发生时存在修改文件的外部进程,则此解决方案可能会失败。更安全的做法是先对所有文件进行stat
处理,然后再进行排序。有关此特定场景的详细信息,请参阅此问题。
UPDATE 2:我很久以前就回答过这个问题了。现在,如果您的c++代码需要与文件系统交互,并且需要在多个操作系统上工作,我强烈建议使用Boost来避免所有跨系统的麻烦。记住,你可以"修剪"。Boost只获取应用程序所需的库;没有必要将整个库套件捆绑在一起。这大大减少了使用Boost的开销。
相关文章:
- 如何计算此排序函数的时间复杂度?
- 保持排序的数据结构,允许log N插入时间,并且可以返回我在log N中查找的元素的索引
- openMp 动态调度与按处理时间排序任务时的 LPT 调度相同吗?
- 列表STL的时间复杂性在一段时间内进行排序
- (C++)合并排序执行时间
- 列表上的气泡排序 - 在计算上花费太多时间
- 在 O(N) 时间内使用布尔谓词函数对向量进行排序
- 计算以毫秒为单位的分类算法对整数阵列排序的时间
- 是否有具有对数时间插入、删除和查找(带距离)的排序数据结构
- 内省排序优于合并排序(时间复杂度)
- C++对向量进行时间复杂度排序
- 为什么使用STL排序()进行二次时间排序
- 按时间对向量进行排序
- 快速排序时间复杂度
- 超过合并 k 排序列表的时间限制(leetcode)
- 堆排序CPU时间
- 如何在时间和空间复杂度的限制下交替对偶数和奇数进行排序?(C/C++)
- 命令模式队列按时间排序
- 快速排序,助手类问题,时间排序,矢量,c++
- c++中文件按修改时间排序