
在Linux中,你可以使用readdir函数来读取目录中的文件和子目录。但是,readdir本身并不提供直接按修改时间排序的功能。要实现这个功能,你需要将读取到的文件信息存储在一个结构体数组中,然后使用qsort函数对这个数组进行排序。
以下是一个简单的示例,展示了如何使用readdir和qsort按修改时间对目录中的文件进行排序:
#<span>include <stdio.h></span>#<span>include <stdlib.h></span>#<span>include <dirent.h></span>#<span>include <sys/stat.h></span>#<span>include <string.h></span>#<span>include <time.h></span>typedef <span>struct {</span> char name[256]; time_t mtime;} FileInfo;int compare(<span>const void *a, const void *b)</span> { FileInfo *fileA = (FileInfo *)a; FileInfo *fileB = (FileInfo *)b; return difftime(fileA->mtime, fileB->mtime);}int main() { DIR *dir; <span>struct dirent *entry;</span> FileInfo files[1024]; dir = opendir("."); if (dir == NULL) { perror("opendir"); return 1; } int i = 0; while ((entry = readdir(dir)) != NULL) { if (entry->d_type == DT_REG) { // 只处理普通文件 <span>struct stat statbuf;</span> char path[1024]; snprintf(path, sizeof(path), "%s/%s", ".", entry->d_name); if (stat(path, &statbuf) == -1) { perror("stat"); continue; } strncpy(files[i].name, entry->d_name, sizeof(files[i].name)); files[i].mtime = statbuf.st_mtime; i++; } } closedir(dir); qsort(files, i, sizeof(FileInfo), compare); for (int j = 0; j < i; j++) { printf("%s: %sn", files[j].name, ctime(&files[j].mtime)); } return 0;}登录后复制
文章来自互联网,不代表电脑知识网立场。发布者:,转载请注明出处:https://www.pcxun.com/n/631840.html
