linux

Linux copendir函数的使用案例

小樊
53
2025-08-28 09:53:38
栏目: 智能运维

copirdir 是一个用于复制目录及其内容的函数,它在 Linux 系统编程中非常有用。以下是一个使用 copirdir 函数的简单示例:

#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string.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)
                return -1;
        } else {
            if (copyfile(srcpath, destpath) == -1)
                return -1;
        }
    }

    closedir(dir);
    return 0;
}

int copyfile(const char *src, const char *dest) {
    FILE *src_file, *dest_file;
    int c;

    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 ((c = fgetc(src_file)) != EOF) {
        if (fputc(c, dest_file) == EOF) {
            perror("fputc");
            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 函数递归地复制源目录及其内容到目标目录。如果复制成功,程序将输出 “Directory copied successfully.”,否则输出 “Failed to copy directory.”。

要编译此程序,请将其保存为 copirdir_example.c,然后在终端中运行以下命令:

gcc -o copirdir_example copirdir_example.c

现在,您可以使用以下命令运行程序:

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

请注意,此示例程序仅用于演示目的,可能无法处理所有边缘情况。在实际应用中,您可能需要根据您的需求对其进行修改。

0
看了该问题的人还看了