首页主机资讯Linux readdir的文件属性获取

Linux readdir的文件属性获取

时间2025-11-22 01:47:04发布访客分类主机资讯浏览1482
导读:在Linux中,readdir函数用于读取目录中的文件和子目录。要获取文件属性,可以使用stat函数。下面是一个简单的示例,展示了如何使用readdir和stat函数获取目录中的文件属性: #include <stdio.h>...

在Linux中,readdir函数用于读取目录中的文件和子目录。要获取文件属性,可以使用stat函数。下面是一个简单的示例,展示了如何使用readdirstat函数获取目录中的文件属性:

#include <
    stdio.h>
    
#include <
    stdlib.h>
    
#include <
    dirent.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 file_path[PATH_MAX];
    
        snprintf(file_path, sizeof(file_path), "%s/%s", argv[1], entry->
    d_name);
    

        // 获取文件属性
        if (stat(file_path, &
file_stat) == -1) {
    
            perror("stat");
    
            continue;

        }
    

        // 输出文件属性
        printf("File: %s\n", entry->
    d_name);
    
        printf("Size: %ld bytes\n", file_stat.st_size);
    
        printf("Last modified: %s", ctime(&
    file_stat.st_mtime));

    }
    

    closedir(dir);
    
    return EXIT_SUCCESS;

}
    

这个程序接受一个目录作为命令行参数,然后使用readdir函数读取目录中的文件和子目录。对于每个文件,它使用stat函数获取文件属性,并输出文件名、大小和最后修改时间。

编译并运行此程序,例如:

gcc file_attributes.c -o file_attributes
./file_attributes /path/to/directory

这将显示指定目录中所有文件的属性。

声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!


若转载请注明出处: Linux readdir的文件属性获取
本文地址: https://pptw.com/jishu/753977.html
Linux readdir的内存使用优化 Linux readdir的时间戳处理

游客 回复需填写必要信息