ubuntu

如何在Ubuntu中有效使用copendir

小樊
41
2025-08-16 11:55:25
栏目: 智能运维

在Ubuntu中,copendir函数用于复制目录及其内容

  1. 首先,确保你的系统已经安装了必要的开发工具和库。在终端中运行以下命令来安装它们:
sudo apt-get update
sudo apt-get install build-essential
  1. 创建一个名为copydir.c的新文件,并使用文本编辑器打开它。例如,你可以使用nano编辑器:
nano copydir.c
  1. 将以下代码粘贴到copydir.c文件中:
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>

void copy_directory_contents(const char *src, const char *dest);

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

    const char *src = argv[1];
    const char *dest = argv[2];

    struct stat st;
    if (stat(src, &st) == -1) {
        perror("Error getting source directory info");
        return 1;
    }

    if (!S_ISDIR(st.st_mode)) {
        printf("Source path is not a directory\n");
        return 1;
    }

    if (mkdir(dest, st.st_mode) == -1 && errno != EEXIST) {
        perror("Error creating destination directory");
        return 1;
    }

    copy_directory_contents(src, dest);

    return 0;
}

void copy_directory_contents(const char *src, const char *dest) {
    DIR *dir = opendir(src);
    if (dir == NULL) {
        perror("Error opening source directory");
        return;
    }

    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 dest_path[PATH_MAX];
        snprintf(dest_path, sizeof(dest_path), "%s/%s", dest, entry->d_name);

        struct stat st;
        if (stat(src_path, &st) == -1) {
            perror("Error getting file info");
            continue;
        }

        if (S_ISDIR(st.st_mode)) {
            mkdir(dest_path, st.st_mode);
            copy_directory_contents(src_path, dest_path);
        } else {
            FILE *src_file = fopen(src_path, "rb");
            FILE *dest_file = fopen(dest_path, "wb");

            if (src_file == NULL || dest_file == NULL) {
                perror("Error opening source or destination file");
                continue;
            }

            char buffer[4096];
            size_t bytes_read;
            while ((bytes_read = fread(buffer, 1, sizeof(buffer), src_file)) > 0) {
                fwrite(buffer, 1, bytes_read, dest_file);
            }

            fclose(src_file);
            fclose(dest_file);
        }
    }

    closedir(dir);
}
  1. 保存并关闭文件。

  2. 在终端中,使用gcc编译器编译copydir.c文件:

gcc -o copydir copydir.c
  1. 现在你可以使用./copydir命令复制目录及其内容。例如:
./copydir /path/to/source/directory /path/to/destination/directory

这将复制source_directory及其所有内容到destination_directory。注意,如果目标目录已存在,它将被覆盖。

0
看了该问题的人还看了