在Linux下,cop*logdir
函数用于复制目录及其内容。当处理符号链接时,cop*logdir
默认会复制符号链接本身,而不是链接指向的目标文件或目录。如果你想要复制符号链接指向的目标内容,可以使用cop*logdir2
函数。
以下是使用cop*logdir
和cop*logdir2
的示例:
cop*logdir
复制目录及其内容(包括符号链接本身):#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
int main() {
DIR *dir;
struct dirent *entry;
struct stat statbuf;
char src_path[1024], dest_path[1024];
dir = opendir(".");
if (dir == NULL) {
perror("opendir");
return 1;
}
while ((entry = readdir(dir)) != NULL) {
snprintf(src_path, sizeof(src_path), "./%s", entry->d_name);
snprintf(dest_path, sizeof(dest_path), "./dest/%s", entry->d_name);
if (lstat(src_path, &statbuf) == -1) {
perror("lstat");
continue;
}
if (S_ISDIR(statbuf.st_mode)) {
mkdir(dest_path, statbuf.st_mode);
cop*logdir(src_path, dest_path, NULL);
} else {
FILE *src_file = fopen(src_path, "rb");
FILE *dest_file = fopen(dest_path, "wb");
if (src_file == NULL || dest_file == NULL) {
perror("fopen");
continue;
}
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;
}
cop*logdir2
复制目录及其内容(包括符号链接指向的目标内容):#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
int main() {
DIR *dir;
struct dirent *entry;
struct stat statbuf;
char src_path[1024], dest_path[1024];
dir = opendir(".");
if (dir == NULL) {
perror("opendir");
return 1;
}
while ((entry = readdir(dir)) != NULL) {
snprintf(src_path, sizeof(src_path), "./%s", entry->d_name);
snprintf(dest_path, sizeof(dest_path), "./dest/%s", entry->d_name);
if (lstat(src_path, &statbuf) == -1) {
perror("lstat");
continue;
}
if (S_ISDIR(statbuf.st_mode)) {
mkdir(dest_path, statbuf.st_mode);
cop*logdir2(src_path, dest_path, NULL, 0);
} else {
FILE *src_file = fopen(src_path, "rb");
FILE *dest_file = fopen(dest_path, "wb");
if (src_file == NULL || dest_file == NULL) {
perror("fopen");
continue;
}
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;
}
请注意,这些示例仅用于演示目的,实际使用时可能需要根据你的需求进行调整。