溫馨提示×

copendir函數如何獲取文件類型

小樊
46
2025-07-06 05:44:10
欄目: 編程語言

copendir 函數本身并不直接提供獲取文件類型的功能。copendir 函數主要用于打開一個目錄流,以便后續使用 readdir 函數讀取目錄中的條目。

要獲取文件類型,你可以使用 readdir 函數讀取目錄條目,然后結合 stat 函數來獲取文件的詳細信息,包括文件類型。以下是一個簡單的示例:

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

int main() {
    DIR *dir;
    struct dirent *entry;
    struct stat file_stat;

    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;
        }

        // 根據 file_stat.st_mode 判斷文件類型
        if (S_ISREG(file_stat.st_mode)) {
            printf("%s is a regular file\n", entry->d_name);
        } else if (S_ISDIR(file_stat.st_mode)) {
            printf("%s is a directory\n", entry->d_name);
        } else if (S_ISCHR(file_stat.st_mode)) {
            printf("%s is a character device\n", entry->d_name);
        } else if (S_ISBLK(file_stat.st_mode)) {
            printf("%s is a block device\n", entry->d_name);
        } else if (S_ISFIFO(file_stat.st_mode)) {
            printf("%s is a FIFO (named pipe)\n", entry->d_name);
        } else if (S_ISSOCK(file_stat.st_mode)) {
            printf("%s is a socket\n", entry->d_name);
        } else {
            printf("%s is of unknown type\n", entry->d_name);
        }
    }

    closedir(dir);
    return EXIT_SUCCESS;
}

這個示例程序會打開當前目錄(.),然后讀取其中的所有條目。對于每個條目,它會使用 stat 函數獲取文件的詳細信息,并根據 st_mode 字段判斷文件類型。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女