溫馨提示×

如何使用Debian readdir獲取文件屬性

小樊
52
2025-03-14 13:15:41
欄目: 智能運維

在Debian系統中,readdir函數通常用于讀取目錄中的文件和子目錄

  1. 首先,確保你的系統已經安裝了C編譯器。如果沒有,請運行以下命令安裝:
sudo apt-get update
sudo apt-get install build-essential
  1. 創建一個名為readdir_example.c的C文件,并在其中編寫以下代碼:
#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) {
        printf("Usage: %s <directory_path>\n", argv[0]);
        return 1;
    }

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

    while ((entry = readdir(dir)) != NULL) {
        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("Name: %s\n", entry->d_name);
        printf("Size: %ld bytes\n", file_stat.st_size);
        printf("Last modified: %s", ctime(&file_stat.st_mtime));
        printf("\n");
    }

    closedir(dir);
    return 0;
}

這段代碼會讀取指定目錄中的所有文件和子目錄,并輸出它們的名稱、大小和最后修改時間。

  1. 使用C編譯器編譯代碼:
gcc readdir_example.c -o readdir_example
  1. 運行編譯后的程序,傳入要讀取的目錄路徑作為參數:
./readdir_example /path/to/directory

程序將輸出指定目錄中所有文件和子目錄的名稱、大小和最后修改時間。

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