在Linux系统中,readdir函数用于读取目录中的条目。要使用readdir实现目录备份,你需要编写一个程序来遍历源目录中的所有文件和子目录,并将它们复制到目标目录。以下是一个简单的示例,展示了如何使用readdir和opendir函数来实现这个功能:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <sys/stat.h>
#include <unistd.h>
void backup_directory(const char *src, const char *dst) {
DIR *dir;
struct dirent *entry;
struct stat statbuf;
char src_path[1024], dst_path[1024];
if (!(dir = opendir(src))) {
perror("opendir");
return;
}
// 创建目标目录(如果不存在)
mkdir(dst, 0755);
while ((entry = readdir(dir)) != NULL) {
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0)
continue;
// 构建源文件/目录的完整路径
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 (stat(src_path, &statbuf) == -1) {
perror("stat");
continue;
}
// 如果是目录,则递归备份
if (S_ISDIR(statbuf.st_mode)) {
backup_directory(src_path, dst_path);
} else {
// 如果是文件,则复制
FILE *src_file = fopen(src_path, "rb");
FILE *dst_file = fopen(dst_path, "wb");
if (!src_file || !dst_file) {
perror("fopen");
continue;
}
char buffer[1024];
size_t n;
while ((n = fread(buffer, 1, sizeof(buffer), src_file)) > 0) {
fwrite(buffer, 1, n, dst_file);
}
fclose(src_file);
fclose(dst_file);
}
}
closedir(dir);
}
int main(int argc, char *argv[]) {
if (argc != 3) {
fprintf(stderr, "Usage: %s <source_directory> <destination_directory>\n", argv[0]);
return 1;
}
backup_directory(argv[1], argv[2]);
return 0;
}
backup.c。gcc -o backup backup.c
./backup /path/to/source /path/to/destination
通过这种方式,你可以使用readdir函数实现一个基本的目录备份工具。