温馨提示×

ubuntu怎么写copendir

小樊
38
2026-08-17 23:23:34
栏目: 智能运维

在 Ubuntu(Linux)里,copendir 不是标准函数,你可能想问的是 如何遍历目录(类似 opendir/readdir/closedir,或者 如何“复制目录”。下面分几种常见情况说明。


一、如果你是想遍历目录(opendir / readdir)

这是 Linux 下最标准的做法,使用 dirent.h

示例:列出目录下的所有文件

#include <stdio.h>
#include <dirent.h>
#include <stdlib.h>

int main() {
    DIR *dir = opendir(".");
    if (dir == NULL) {
        perror("opendir");
        return 1;
    }

    struct dirent *entry;
    while ((entry = readdir(dir)) != NULL) {
        printf("%s\n", entry->d_name);
    }

    closedir(dir);
    return 0;
}

编译运行

gcc listdir.c -o listdir
./listdir

二、如果你是想复制目录(copy directory)

Linux 没有 copendir(),复制目录需要:

  1. opendir 打开源目录
  2. readdir 读取内容
  3. 对文件用 open/read/write
  4. 对子目录递归 mkdir

简单示例(递归复制目录)

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

void copy_file(const char *src, const char *dst) {
    int fd_src = open(src, O_RDONLY);
    int fd_dst = open(dst, O_WRONLY | O_CREAT | O_TRUNC, 0644);

    char buf[4096];
    ssize_t n;
    while ((n = read(fd_src, buf, sizeof(buf))) > 0) {
        write(fd_dst, buf, n);
    }

    close(fd_src);
    close(fd_dst);
}

void copy_dir(const char *src, const char *dst) {
    mkdir(dst, 0755);
    DIR *dir = opendir(src);
    struct dirent *entry;

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

        char src_path[512], dst_path[512];
        snprintf(src_path, sizeof(src_path), "%s/%s", src, entry->d_name);
        snprintf(dst_path, sizeof(dst_path), "%s/%s", dst, entry->d_name);

        struct stat st;
        lstat(src_path, &st);

        if (S_ISDIR(st.st_mode)) {
            copy_dir(src_path, dst_path);
        } else {
            copy_file(src_path, dst_path);
        }
    }
    closedir(dir);
}

int main() {
    copy_dir("test", "test_copy");
    return 0;
}

三、如果你只是想在命令行复制目录

不需要写 C 程序:

cp -r src_dir dst_dir

四、常见误区说明

没有 copendir 这个函数
✅ 正确的是:

  • opendir
  • readdir
  • closedir

如果你是在 Windows 看到过类似 copendir,那是第三方封装,不是 Linux API。


五、我可以进一步帮你

你可以告诉我:

  • C 程序 还是 Shell 脚本
  • 遍历目录 还是 复制目录
  • 是否需要 递归 / 过滤文件类型

我可以直接给你一个可用的完整版本。

0