在Ubuntu系统中,使用readdir
函数可以帮助你遍历目录并获取其中的文件列表。结合其他文件操作函数,你可以实现一个简单的文件备份功能。以下是一个基本的示例代码,展示了如何使用readdir
函数来遍历目录并复制文件到备份目录中。
首先,确保你有必要的权限来读取源目录和写入备份目录。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
void backup_directory(const char *source_dir, const char *backup_dir) {
DIR *dir;
struct dirent *entry;
char source_path[1024], backup_path[1024];
// 打开源目录
if (!(dir = opendir(source_dir))) {
perror("opendir");
return;
}
// 创建备份目录(如果不存在)
mkdir(backup_dir, 0700);
// 遍历目录中的每个条目
while ((entry = readdir(dir)) != NULL) {
// 跳过当前目录和上级目录
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
continue;
}
// 构建源文件路径和备份文件路径
snprintf(source_path, sizeof(source_path), "%s/%s", source_dir, entry->d_name);
snprintf(backup_path, sizeof(backup_path), "%s/%s", backup_dir, entry->d_name);
// 检查是否是目录
struct stat statbuf;
if (stat(source_path, &statbuf) == -1) {
perror("stat");
continue;
}
if (S_ISDIR(statbuf.st_mode)) {
// 如果是目录,递归调用备份函数
backup_directory(source_path, backup_path);
} else {
// 如果是文件,复制文件
int src_fd = open(source_path, O_RDONLY);
if (src_fd == -1) {
perror("open");
continue;
}
int backup_fd = open(backup_path, O_WRONLY | O_CREAT, 0644);
if (backup_fd == -1) {
perror("open");
close(src_fd);
continue;
}
char buffer[1024];
ssize_t bytes_read, bytes_written;
while ((bytes_read = read(src_fd, buffer, sizeof(buffer))) > 0) {
bytes_written = write(backup_fd, buffer, bytes_read);
if (bytes_written != bytes_read) {
perror("write");
break;
}
}
close(src_fd);
close(backup_fd);
}
}
closedir(dir);
}
int main(int argc, char *argv[]) {
if (argc != 3) {
fprintf(stderr, "Usage: %s <source_directory> <backup_directory>\n", argv[0]);
return 1;
}
const char *source_dir = argv[1];
const char *backup_dir = argv[2];
backup_directory(source_dir, backup_dir);
return 0;
}
backup.c
。gcc -o backup backup.c
./backup /path/to/source /path/to/backup
通过这种方式,你可以使用readdir
函数来实现一个简单的文件备份功能。