ubuntu

ubuntu readdir如何实现文件统计信息

小樊
42
2025-12-29 17:23:38
栏目: 智能运维

在Ubuntu系统中,你可以使用readdir函数来读取目录中的文件和子目录。为了实现文件统计信息,你需要遍历目录并统计所需的文件类型、大小等信息。以下是一个简单的示例,展示了如何使用readdir函数统计目录中的文件数量:

#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/stat.h>

int main(int argc, char *argv[]) {
    if (argc != 2) {
        printf("Usage: %s <directory_path>\n", argv[0]);
        return 1;
    }

    DIR *dir = opendir(argv[1]);
    if (dir == NULL) {
        perror("opendir");
        return 1;
    }

    struct dirent *entry;
    int file_count = 0;

    while ((entry = readdir(dir)) != NULL) {
        if (entry->d_type == DT_REG) { // 只统计普通文件
            file_count++;
        }
    }

    closedir(dir);

    printf("Total files in directory '%s': %d\n", argv[1], file_count);
    return 0;
}

要编译此程序,请将其保存为count_files.c,然后在终端中运行以下命令:

gcc count_files.c -o count_files

现在你可以使用此程序来统计目录中的文件数量:

./count_files /path/to/directory

如果你需要统计其他类型的文件(如目录、符号链接等),可以根据entry->d_type的值进行相应的判断。有关d_type的详细信息,请参阅dirent.h头文件中的文档。

此外,如果你需要获取更多关于文件的详细信息(如文件大小、修改时间等),可以使用stat函数。以下是一个简单的示例,展示了如何使用stat函数获取文件的大小:

#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>

int main(int argc, char *argv[]) {
    if (argc != 2) {
        printf("Usage: %s <file_path>\n", argv[0]);
        return 1;
    }

    struct stat file_stat;
    int result = stat(argv[1], &file_stat);

    if (result == 0) {
        printf("File size of '%s': %ld bytes\n", argv[1], file_stat.st_size);
    } else {
        perror("stat");
        return 1;
    }

    return 0;
}

要编译此程序,请将其保存为get_file_size.c,然后在终端中运行以下命令:

gcc get_file_size.c -o get_file_size

现在你可以使用此程序来获取文件的大小:

./get_file_size /path/to/file

0
看了该问题的人还看了