Currently I am using dirent.h to iterativly access files in a directory and its sub-directories. It accesses them according to their file names (alphabetically). For some reason I want to access the subdirectories and the files according to their modification time (with the latest modified file being accessed at last). Is it possible to do so?
I am thinking to first traverse through the directories and create a sorted list of the files according to their modification time and use this list to read them accordingly. But I was hoping if there is a better way.
Based on my first thinking and as per the suggestion in the comments.
#include<dirent.h>
typedef struct files {
long long mtime;
string file_path;
bool operator<(const files &rhs)const {
return mtime < rhs.mtime;
}
}files;
using namespace std;
vector<struct files> files_list;
void build_files_list(const char *path) {
struct dirent *entry;
DIR *dp;
if (dp = opendir(path)) {
struct _stat64 buf;
while ((entry = readdir(dp))){
std::string p(path);
p += "\\";
p += entry->d_name;
if (!_stat64(p.c_str(), &buf)){
if (S_ISREG(buf.st_mode)){
files new_file;
new_file.mtime = buf.st_mtime;
new_file.file_path = entry->d_name;
files.push_back(new_file);
}
if (S_ISDIR(buf.st_mode) &&
// the following is to ensure we do not dive into directories "." and ".."
strcmp(entry->d_name, ".") && strcmp(entry->d_name, "..")){
//do nothing
}
}
}
closedir(dp);
}
else{
printf_s("\n\tERROR in openning dir %s\n\n\tPlease enter a correct
directory", path);
}
}
void main(){
char *dir_path="dir_path";
build_files_list(dir_path);
sort(files_list.begin(), files_list.end());
//the rest of things to do
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.