溫馨提示×

如何使用 Debian readdir 進行批量操作

小樊
41
2025-07-13 14:58:13
欄目: 智能運維

在 Debian 系統中,readdir 是一個用于讀取目錄內容的函數,通常在 C 語言編程中使用

  1. 首先,確保你已經安裝了必要的開發工具和庫。在 Debian 上,你可以使用以下命令安裝:
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 <string.h>

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

    char *path = argv[1];
    DIR *dir = opendir(path);

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

    struct dirent *entry;
    while ((entry = readdir(dir)) != NULL) {
        printf("%s\n", entry->d_name);
    }

    closedir(dir);
    return 0;
}

這段代碼會讀取指定目錄下的所有文件和子目錄,并將它們的名稱打印到控制臺。

  1. 使用 gcc 編譯源文件:
gcc readdir_example.c -o readdir_example
  1. 運行編譯后的程序,指定要讀取的目錄路徑:
./readdir_example /path/to/directory

這將輸出指定目錄下的所有文件和子目錄。

如果你想要對目錄中的文件執行批量操作,可以在 while 循環中添加相應的代碼。例如,如果你想要刪除目錄中的所有 .txt 文件,可以使用以下代碼:

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

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

    char *path = argv[1];
    DIR *dir = opendir(path);

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

    struct dirent *entry;
    while ((entry = readdir(dir)) != NULL) {
        if (strstr(entry->d_name, ".txt")) {
            char file_path[1024];
            snprintf(file_path, sizeof(file_path), "%s/%s", path, entry->d_name);

            if (remove(file_path) != 0) {
                perror("remove");
            } else {
                printf("Deleted: %s\n", file_path);
            }
        }
    }

    closedir(dir);
    return 0;
}

這段代碼會刪除指定目錄下的所有 .txt 文件。請注意,在執行批量操作時要小心,以免誤刪重要文件。在實際使用中,建議先在測試目錄中進行嘗試。

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