copysdir 函数在 Linux 中用于复制目录及其内容。为了确保最佳实践,以下是一些建议和注意事项:
copysdir 返回一个整数,表示操作是否成功。perror 或 strerror 来获取错误信息。#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <sys/stat.h>
#include <dirent.h>
#include <unistd.h>
int copysdir(const char *src, const char *dst) {
DIR *dir = opendir(src);
if (!dir) {
perror("opendir");
return -1;
}
struct stat st;
if (stat(src, &st) != 0) {
perror("stat");
closedir(dir);
return -1;
}
if (!S_ISDIR(st.st_mode)) {
fprintf(stderr, "%s is not a directory\n", src);
closedir(dir);
return -1;
}
if (mkdir(dst, st.st_mode) != 0 && errno != EEXIST) {
perror("mkdir");
closedir(dir);
return -1;
}
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];
char dst_path[PATH_MAX];
snprintf(src_path, sizeof(src_path), "%s/%s", src, entry->d_name);
snprintf(dst_path, sizeof(dst_path), "%s/%s", dst, entry->d_name);
if (copysdir(src_path, dst_path) != 0) {
closedir(dir);
return -1;
}
}
closedir(dir);
return 0;
}
int main(int argc, char *argv[]) {
if (argc != 3) {
fprintf(stderr, "Usage: %s <source_directory> <destination_directory>\n", argv[0]);
return EXIT_FAILURE;
}
if (copysdir(argv[1], argv[2]) != 0) {
fprintf(stderr, "Failed to copy directory\n");
return EXIT_FAILURE;
}
printf("Directory copied successfully\n");
return EXIT_SUCCESS;
}
copysdir 应该复制符号链接本身而不是链接指向的目标。lstat 来检查文件类型,如果是符号链接,则使用 readlink 来读取链接目标并创建新的符号链接。chown 和 chmod 来设置目标文件和目录的所有权和权限。errno 来获取具体的错误代码,并使用 strerror 来转换为可读的错误信息。通过遵循这些最佳实践,可以确保 copysdir 函数在 Linux 系统中安全、高效地工作。