alt="linux copendir如何获取文件修改时间" />
在Linux中,copendir()函数用于打开一个目录流,以便使用readdir()函数读取目录中的条目。要获取文件的修改时间,您需要使用stat()函数。以下是一个简单的示例,展示了如何使用copendir()和stat()函数获取目录中文件的修改时间:
#<span>include <stdio.h></span>#<span>include <stdlib.h></span>#<span>include <dirent.h></span>#<span>include <sys/stat.h></span>#<span>include <unistd.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; } // 获取文件的stat结构 if (stat(entry->d_name, &file_stat) == -1) { perror("stat"); continue; } // 打印文件名和修改时间 char time_buf[26]; strftime(time_buf, sizeof(time_buf), "%Y-%m-%d %H:%M:%S", localtime(&file_stat.st_mtime)); printf("%s: %sn", entry->d_name, time_buf); } closedir(dir); return EXIT_SUCCESS;}
登录后复制
文章来自互联网,不代表电脑知识网立场。发布者:,转载请注明出处:https://www.pcxun.com/n/651993.html