溫馨提示×

copendir函數在Linux中的使用案例

小樊
41
2025-10-14 20:10:41
欄目: 智能運維

copirdir 函數是 Linux 系統中的一個庫函數,用于遞歸地復制目錄及其內容。它位于 <dirent.h> 頭文件中。以下是一個使用 copirdir 函數的簡單示例:

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

int copirdir(const char *src, const char *dest) {
    DIR *dir;
    struct dirent *entry;
    struct stat statbuf;
    char srcpath[PATH_MAX], destpath[PATH_MAX];

    if (!(dir = opendir(src))) {
        perror("opendir");
        return -1;
    }

    if (mkdir(dest, statbuf.st_mode) == -1) {
        perror("mkdir");
        closedir(dir);
        return -1;
    }

    while ((entry = readdir(dir)) != NULL) {
        if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
            continue;
        }

        snprintf(srcpath, sizeof(srcpath), "%s/%s", src, entry->d_name);
        snprintf(destpath, sizeof(destpath), "%s/%s", dest, entry->d_name);

        if (lstat(srcpath, &statbuf) == -1) {
            perror("lstat");
            closedir(dir);
            return -1;
        }

        if (S_ISDIR(statbuf.st_mode)) {
            if (copirdir(srcpath, destpath) == -1) {
                closedir(dir);
                return -1;
            }
        } else {
            if (copyfile(srcpath, destpath) == -1) {
                closedir(dir);
                return -1;
            }
        }
    }

    closedir(dir);
    return 0;
}

int copyfile(const char *src, const char *dest) {
    FILE *src_file, *dest_file;
    char buffer[BUFSIZ];

    src_file = fopen(src, "rb");
    if (!src_file) {
        perror("fopen");
        return -1;
    }

    dest_file = fopen(dest, "wb");
    if (!dest_file) {
        perror("fopen");
        fclose(src_file);
        return -1;
    }

    while (size_t n = fread(buffer, sizeof(char), sizeof(buffer), src_file)) {
        if (fwrite(buffer, sizeof(char), n, dest_file) != n) {
            perror("fwrite");
            fclose(src_file);
            fclose(dest_file);
            return -1;
        }
    }

    fclose(src_file);
    fclose(dest_file);
    return 0;
}

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

    if (copirdir(argv[1], argv[2]) == 0) {
        printf("Directory copied successfully.\n");
    } else {
        fprintf(stderr, "Failed to copy directory.\n");
        return 1;
    }

    return 0;
}

這個示例程序接受兩個命令行參數:源目錄和目標目錄。它使用 copirdir 函數遞歸地復制源目錄及其內容到目標目錄。如果在復制過程中遇到任何問題,程序將返回錯誤代碼并顯示相應的錯誤消息。

要編譯此程序,請將其保存為 copirdir_example.c,然后在終端中運行以下命令:

gcc -o copirdir_example copirdir_example.c

現在,您可以使用以下命令運行程序:

./copirdir_example /path/to/source/directory /path/to/destination/directory

請注意,這個示例程序僅用于演示目的,可能無法處理所有邊緣情況。在實際應用中,您可能需要根據您的需求對其進行修改和優化。

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