
在C语言中,你可以使用readdir函数来读取目录中的文件和子目录。但是,readdir本身并不直接提供文件的修改时间。要获取文件的修改时间,你需要使用stat函数。
以下是一个简单的示例,展示了如何使用readdir和stat来获取目录中文件的修改时间:
#<span>include <stdio.h></span>#<span>include <stdlib.h></span>#<span>include <dirent.h></span>#<span>include <sys/stat.h></span>#<span>include <time.h></span>int main() { DIR *dir; <span>struct dirent *entry;</span> <span>struct stat file_stat;</span> // 打开目录 dir = opendir("."); if (dir == NULL) { perror("opendir"); return EXIT_FAILURE; } // 读取目录中的条目 while ((entry = readdir(dir)) != NULL) { // 跳过当前目录和上级目录的特殊条目 if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) { continue; } // 构建文件的完整路径 char path[PATH_MAX]; snprintf(path, sizeof(path), "./%s", entry->d_name); // 获取文件的状态信息 if (stat(path, &file_stat) == -1) { perror("stat"); continue; } // 打印文件名和修改时间 char time_buf[26]; ctime_r(&file_stat.st_mtime, time_buf); time_buf[strcspn(time_buf, "")] = 0; // 去掉换行符 printf("%s - Modified: %s", entry->d_name, time_buf); } // 关闭目录 closedir(dir); return EXIT_SUCCESS;}登录后复制
文章来自互联网,不代表电脑知识网立场。发布者:,转载请注明出处:https://www.pcxun.com/n/703952.html
