溫馨提示×

linux readdir如何與stat配合使用

小樊
107
2024-12-29 09:39:24
欄目: 智能運維

在Linux中,readdirstat是兩個常用的系統調用,分別用于讀取目錄內容和獲取文件/目錄的元數據

  1. 首先,使用opendir函數打開一個目錄:
DIR *dir = opendir("directory_path");
if (!dir) {
    perror("opendir");
    return 1;
}
  1. 使用readdir函數逐個讀取目錄中的條目(文件和子目錄):
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
    // 處理每個目錄條目
}
  1. 對于每個目錄條目,使用stat函數獲取其元數據:
struct stat file_stat;
if (stat(entry->d_name, &file_stat) == -1) {
    perror("stat");
    continue;
}
  1. 現在,你可以使用file_stat結構體中的成員變量來獲取文件/目錄的各種信息,例如:
  • file_stat.st_mode:文件類型和權限
  • file_stat.st_nlink:文件鏈接數
  • file_stat.st_uid:文件所有者ID
  • file_stat.st_gid:文件所屬組ID
  • file_stat.st_size:文件大?。ㄗ止潱?/li>
  • file_stat.st_mtime:文件最后修改時間(秒)
  • file_stat.st_ctime:文件狀態更改時間(秒)

下面是一個完整的示例程序,演示了如何將readdirstat配合使用:

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

int main() {
    DIR *dir = opendir("directory_path");
    if (!dir) {
        perror("opendir");
        return 1;
    }

    struct dirent *entry;
    while ((entry = readdir(dir)) != NULL) {
        struct stat file_stat;
        if (stat(entry->d_name, &file_stat) == -1) {
            perror("stat");
            continue;
        }

        printf("Filename: %s\n", entry->d_name);
        printf("Size: %ld bytes\n", (long)file_stat.st_size);
        printf("Last modified: %s", ctime(&file_stat.st_mtime));
        printf("\n");
    }

    closedir(dir);
    return 0;
}

directory_path替換為你要讀取的目錄路徑,然后編譯并運行程序。它將顯示目錄中每個文件和子目錄的名稱、大小和最后修改時間。

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