在Linux系统中,readdir函数通常用于读取目录的内容。如果你想要利用readdir来进行文件备份,你需要编写一个程序来遍历源目录中的所有文件和子目录,并将它们复制到目标目录中。以下是一个简单的示例,展示了如何使用C语言和readdir函数来实现基本的文件备份功能:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <sys/stat.h>
#include <unistd.h>
// 函数声明
void backup_file(const char *src, const char *dst);
void copy_directory(const char *src, const char *dst);
int main(int argc, char *argv[]) {
if (argc != 3) {
fprintf(stderr, "Usage: %s <source_directory> <destination_directory>\n", argv[0]);
return EXIT_FAILURE;
}
const char *source_dir = argv[1];
const char *destination_dir = argv[2];
// 检查源目录是否存在
struct stat st = {0};
if (stat(source_dir, &st) != 0 || !S_ISDIR(st.st_mode)) {
fprintf(stderr, "Source directory does not exist or is not a directory.\n");
return EXIT_FAILURE;
}
// 创建目标目录(如果不存在)
if (mkdir(destination_dir, 0755) != 0 && errno != EEXIST) {
perror("mkdir");
return EXIT_FAILURE;
}
// 复制目录内容
copy_directory(source_dir, destination_dir);
return EXIT_SUCCESS;
}
void backup_file(const char *src, const char *dst) {
FILE *source = fopen(src, "rb");
FILE *destination = fopen(dst, "wb");
if (!source || !destination) {
perror("Error opening files for copying");
return;
}
char buffer[4096];
size_t bytes_read;
while ((bytes_read = fread(buffer, 1, sizeof(buffer), source)) > 0) {
fwrite(buffer, 1, bytes_read, destination);
}
fclose(source);
fclose(destination);
}
void copy_directory(const char *src, const char *dst) {
DIR *dir = opendir(src);
if (!dir) {
perror("opendir");
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];
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);
struct stat st;
if (stat(src_path, &st) != 0) {
perror("stat");
continue;
}
if (S_ISDIR(st.st_mode)) {
// 如果是目录,则递归复制
backup_file(src_path, dst_path); // 复制目录本身
copy_directory(src_path, dst_path); // 递归复制子目录内容
} else {
// 如果是文件,则直接复制
backup_file(src_path, dst_path);
}
}
closedir(dir);
}
这个程序接受两个命令行参数:源目录和目标目录。它会遍历源目录中的所有文件和子目录,并将它们复制到目标目录中。对于子目录,它会先创建相应的目录结构,然后递归地复制其中的文件。
请注意,这个示例程序是一个简单的实现,它没有处理所有的边缘情况,例如符号链接、权限问题、错误处理等。在实际使用中,你可能需要根据具体情况对程序进行相应的修改和增强。此外,对于大型文件或大量文件的备份,可能需要考虑更高效的文件复制方法,例如使用sendfile系统调用或者多线程/多进程来提高性能。