在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。注意,如果目标目录已存在,它将被覆盖。
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,请发送邮件至 55@qq.com 举报,一经查实,本站将立刻删除。转转请注明出处:https://www.szhjjp.com/n/1390829.html