温馨提示×

copendir函数在Linux中的使用案例

小樊
46
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