溫馨提示×

copendir函數的使用示例

小樊
50
2025-08-16 07:53:20
欄目: 編程語言

copirdir 函數用于復制目錄及其內容。它通常在 POSIX 兼容的系統上可用,例如 Linux 和 macOS。該函數會遞歸地復制源目錄中的所有文件和子目錄到目標目錄。

以下是一個使用 copirdir 函數的簡單示例:

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

// 遞歸復制目錄
int copy_directory(const char *src, const char *dest) {
    DIR *dir = opendir(src);
    struct dirent *entry;
    struct stat statbuf;
    char path[1024];

    // 檢查源目錄是否可以打開
    if (!dir) {
        perror("opendir");
        return -1;
    }

    // 創建目標目錄
    if (mkdir(dest, statbuf.st_mode) == -1) {
        if (errno != EEXIST) {
            perror("mkdir");
            closedir(dir);
            return -1;
        }
    }

    // 遍歷目錄中的每個條目
    while ((entry = readdir(dir)) != NULL) {
        if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0)
            continue;

        // 構建完整路徑
        snprintf(path, sizeof(path), "%s/%s", src, entry->d_name);

        // 獲取文件信息
        if (stat(path, &statbuf) == -1) {
            perror("stat");
            closedir(dir);
            return -1;
        }

        // 如果是目錄,遞歸復制
        if (S_ISDIR(statbuf.st_mode)) {
            if (copy_directory(path, dest) == -1)
                return -1;
        } else {
            // 如果是普通文件,直接復制
            FILE *src_file = fopen(path, "rb");
            FILE *dest_file = fopen(dest_path, "wb");

            if (!src_file || !dest_file) {
                perror("fopen");
                closedir(dir);
                return -1;
            }

            char buffer[1024];
            size_t n;

            while ((n = fread(buffer, 1, sizeof(buffer), src_file)) > 0) {
                fwrite(buffer, 1, n, dest_file);
            }

            fclose(src_file);
            fclose(dest_file);
        }
    }

    closedir(dir);
    return 0;
}

int main(int argc, char *argv[]) {
    if (argc != 3) {
        fprintf(stderr, "Usage: %s <source_directory> <destination_directory>
", argv[0]);
        return EXIT_FAILURE;
    }

    const char *src_dir = argv[1];
    const char *dest_dir = argv[2];

    if (copy_directory(src_dir, dest_dir) == 0) {
        printf("Directory copied successfully.
");
    } else {
        fprintf(stderr, "Failed to copy directory.
");
        return EXIT_FAILURE;
    }

    return EXIT_SUCCESS;
}

說明:

  • opendir:打開一個目錄流。
  • readdir:讀取目錄中的下一個條目。
  • stat:獲取文件或目錄的信息。
  • mkdir:創建一個新的目錄。
  • fopen, fread, fwrite, fclose:用于文件的讀寫操作。

注意:

  • 上面的示例沒有處理符號鏈接、權限問題和其他可能的錯誤情況。
  • 在實際應用中,可能需要更復雜的錯誤處理和更多的功能(如保留文件屬性等)。
  • copirdir 不是標準 C 庫函數,而是某些系統特定的擴展。在標準 POSIX 中,通常使用 cp -r 命令行工具來復制目錄。

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