alt="linux readdir如何实现文件属性获取" />
在Linux系统中,readdir函数被用来读取目录里的文件及子目录信息。若想获取文件属性,则需配合stat函数共同完成。下面是一个简单的代码示例,展示如何利用readdir与stat函数来取得目录内文件的属性:
#include <stdio.h>#include <stdlib.h>#include <dirent.h>#include <sys/types.h>#include <sys/stat.h>#include <unistd.h>int main(int argc, char *argv[]) { DIR *dir; struct dirent *entry; struct stat file_stat; if (argc != 2) { fprintf(stderr, "Usage: %s <directory>n", argv[0]); return EXIT_FAILURE; } dir = opendir(argv[1]); 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/%s", argv[1], entry->d_name); // 获取文件属性 if (stat(path, &file_stat) == -1) { perror("stat"); continue; } // 显示文件属性 printf("File: %sn", entry->d_name); printf("Size: %ld bytesn", file_stat.st_size); printf("Last modified: %s", ctime(&file_stat.st_mtime)); } closedir(dir); return EXIT_SUCCESS;}
登录后复制
文章来自互联网,不代表电脑知识网立场。发布者:,转载请注明出处:https://www.pcxun.com/n/659439.html