在Ubuntu中,copendir
函数用于复制目录及其内容
sudo apt-get update sudo apt-get install build-essential
copydir.c
的新文件,并使用文本编辑器打开它。例如,你可以使用nano编辑器:nano copydir.c
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); }
保存并关闭文件。
在终端中,使用gcc
编译器编译copydir.c
文件:
gcc -o copydir copydir.c
./copydir
命令复制目录及其内容。例如:./copydir /path/to/source/directory /path/to/destination/directory
这将复制source_directory
及其所有内容到destination_directory
。注意,如果目标目录已存在,它将被覆盖。