在Linux中,readdir
函数用于读取目录中的条目。要使用readdir
实现文件备份,你需要遍历源目录中的所有文件和子目录,并将它们复制到目标目录。以下是一个简单的示例,展示了如何使用readdir
实现文件备份:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <sys/stat.h>
#include <unistd.h>
#include <sys/types.h>
void backup_file(const char *src, const char *dst) {
FILE *src_file = fopen(src, "rb");
FILE *dst_file = fopen(dst, "wb");
if (!src_file || !dst_file) {
perror("Error opening files");
return;
}
char buffer[4096];
size_t bytes_read;
while ((bytes_read = fread(buffer, 1, sizeof(buffer), src_file)) > 0) {
fwrite(buffer, 1, bytes_read, dst_file);
}
fclose(src_file);
fclose(dst_file);
}
void backup_directory(const char *src_dir, const char *dst_dir) {
struct dirent *entry;
DIR *dir = opendir(src_dir);
if (!dir) {
perror("Error opening directory");
return;
}
// 创建目标目录(如果不存在)
mkdir(dst_dir, 0755);
while ((entry = readdir(dir)) != NULL) {
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
continue;
}
char src_path[1024], dst_path[1024];
snprintf(src_path, sizeof(src_path), "%s/%s", src_dir, entry->d_name);
snprintf(dst_path, sizeof(dst_path), "%s/%s", dst_dir, entry->d_name);
struct stat st;
stat(src_path, &st);
if (S_ISDIR(st.st_mode)) {
backup_directory(src_path, dst_path);
} else {
backup_file(src_path, dst_path);
}
}
closedir(dir);
}
int main(int argc, char *argv[]) {
if (argc != 3) {
printf("Usage: %s <source_directory> <destination_directory>\n", argv[0]);
return 1;
}
const char *src_dir = argv[1];
const char *dst_dir = argv[2];
backup_directory(src_dir, dst_dir);
return 0;
}
这个程序接受两个命令行参数:源目录和目标目录。它首先创建目标目录(如果不存在),然后遍历源目录中的所有条目。对于每个条目,它检查是否是目录。如果是目录,它递归调用backup_directory
函数;否则,它调用backup_file
函数来复制文件。
要编译此程序,请将其保存为backup.c
,然后运行以下命令:
gcc -o backup backup.c
现在你可以使用以下命令运行备份程序:
./backup <source_directory> <destination_directory>
请注意,这个程序不会处理符号链接、设备文件等特殊文件类型。你可能需要根据你的需求对其进行扩展。