如何检查copendir是否成功

如何检查copendir是否成功

在C语言中,并没有标准的copdir函数用于复制目录。你可能混淆了opendir和readdir这类用于遍历目录的函数,以及mkdir用于创建目录的函数。要实现目录复制并验证其是否成功,通常需要手动编写代码完成。

下面是一个简单的示例,演示如何判断目录复制操作是否成功:

#include <stdio.h>#include <stdlib.h>#include <string.h>#include <dirent.h>#include <sys/stat.h>#include <sys/types.h>#include <unistd.h>int copy_directory_contents(const char *src, const char *dst) {    DIR *dir = opendir(src);    if (dir == NULL) {        perror("opendir");        return -1;    }    struct dirent *entry;    while ((entry = readdir(dir)) != NULL) {        if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {            continue; // 跳过当前和上级目录        }        char src_path[PATH_MAX];        snprintf(src_path, sizeof(src_path), "%s/%s", src, entry->d_name);        char dst_path[PATH_MAX];        snprintf(dst_path, sizeof(dst_path), "%s/%s", dst, entry->d_name);        struct stat st;        if (stat(src_path, &st) == -1) {            perror("stat");            closedir(dir);            return -1;        }        if (S_ISDIR(st.st_mode)) {            // 如果是子目录,则在目标位置创建对应目录            if (mkdir(dst_path, st.st_mode) != 0) {                perror("mkdir");                closedir(dir);                return -1;            }        } else {            // 如果是文件,则执行复制操作            FILE *src_file = fopen(src_path, "rb");            if (src_file == NULL) {                perror("fopen");                closedir(dir);                return -1;            }            FILE *dst_file = fopen(dst_path, "wb");            if (dst_file == NULL) {                perror("fopen");                fclose(src_file);                closedir(dir);                return -1;            }            char buffer[4096];            size_t bytes_read;            while ((bytes_read = fread(buffer, 1, sizeof(buffer), src_file)) > 0) {                if (fwrite(buffer, 1, bytes_read, dst_file) != bytes_read) {                    perror("fwrite");                    fclose(src_file);                    fclose(dst_file);                    closedir(dir);                    return -1;                }            }            fclose(src_file);            fclose(dst_file);        }    }    closedir(dir);    // 复制目录权限属性    if (chmod(dst, st.st_mode) != 0) {        perror("chmod");        return -1;    }    return 0;}int main(int argc, char *argv[]) {    if (argc != 3) {        fprintf(stderr, "用法: %s  <目标目录>n", argv[0]);        return EXIT_FAILURE;    }    const char *src_dir = argv[1];    const char *dst_dir = argv[2];    if (copy_directory_contents(src_dir, dst_dir) == 0) {        printf("目录复制成功。n");    } else {        fprintf(stderr, "目录复制失败。n");        return EXIT_FAILURE;    }    return EXIT_SUCCESS;}</target></target>

登录后复制

文章来自互联网,不代表电脑知识网立场。发布者:,转载请注明出处:https://www.pcxun.com/n/732242.html

(0)
上一篇 2025-06-13 12:05
下一篇 2025-06-13 12:05

相关推荐