copendir
是一个在 C 语言中用于复制目录的函数,它属于 POSIX 标准库。在使用 Ubuntu 时,如果你想在 C 程序中使用 cop*logdir
函数来复制目录,你需要遵循以下步骤:
sudo apt-get update
sudo apt-get install build-essential
copy_directory.c
),并在文件中包含必要的头文件:#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>
int copy_directory(const char *src, const char *dest) {
DIR *dir = opendir(src);
if (!dir) {
perror("opendir");
return -1;
}
struct stat st = {0};
if (stat(dest, &st) == -1) {
mkdir(dest, 0755);
}
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
continue;
}
char src_path[1024], dest_path[1024];
snprintf(src_path, sizeof(src_path), "%s/%s", src, entry->d_name);
snprintf(dest_path, sizeof(dest_path), "%s/%s", dest, entry->d_name);
if (stat(src_path, &st) == -1) {
perror("stat");
closedir(dir);
return -1;
}
if (S_ISDIR(st.st_mode)) {
copy_directory(src_path, dest_path);
} else {
FILE *src_file = fopen(src_path, "rb");
FILE *dest_file = fopen(dest_path, "wb");
if (!src_file || !dest_file) {
perror("fopen");
closedir(dir);
return -1;
}
char buffer[1024];
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);
return 0;
}
main
函数中调用 copy_directory
函数: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];
if (copy_directory(src, dest) == 0) {
printf("Directory copied successfully.\n");
} else {
printf("Failed to copy directory.\n");
}
return 0;
}
gcc -o copy_directory copy_directory.c
./copy_directory /path/to/source/directory /path/to/destination/directory
请注意,这个示例程序没有处理所有可能的错误情况,你可能需要根据你的需求进行调整。