在Ubuntu系统中,使用readdir函数可以实现遍历目录并获取目录中的文件列表。要实现文件备份功能,你可以结合readdir函数和其他文件操作函数(如fopen、fread、fwrite等)来读取源目录中的文件,并将它们复制到目标目录。
以下是一个简单的示例,展示了如何使用readdir函数实现文件备份功能:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
int copy_file(const char *src, const char *dst) {
int src_fd = open(src, O_RDONLY);
if (src_fd < 0) {
perror("open source file");
return -1;
}
int dst_fd = open(dst, O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR);
if (dst_fd < 0) {
perror("open destination file");
close(src_fd);
return -1;
}
char buffer[4096];
ssize_t n;
while ((n = read(src_fd, buffer, sizeof(buffer))) > 0) {
if (write(dst_fd, buffer, n) != n) {
perror("write to destination file");
close(src_fd);
close(dst_fd);
return -1;
}
}
if (n < 0) {
perror("read from source file");
close(src_fd);
close(dst_fd);
return -1;
}
close(src_fd);
close(dst_fd);
return 0;
}
int main(int argc, char *argv[]) {
if (argc != 3) {
fprintf(stderr, "Usage: %s <source_directory> <destination_directory>\n", argv[0]);
return 1;
}
const char *src_dir = argv[1];
const char *dst_dir = argv[2];
struct dirent *entry;
DIR *dp = opendir(src_dir);
if (!dp) {
perror("opendir");
return 1;
}
while ((entry = readdir(dp))) {
if (entry->d_type == DT_REG) { // Only process regular files
char src_path[PATH_MAX], dst_path[PATH_MAX];
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);
if (copy_file(src_path, dst_path) < 0) {
fprintf(stderr, "Failed to copy file: %s\n", src_path);
}
}
}
closedir(dp);
return 0;
}
这个程序接受两个命令行参数:源目录和目标目录。它遍历源目录中的所有文件,并将它们复制到目标目录。请注意,这个示例仅适用于普通文件,不包括子目录。如果你需要处理子目录,可以使用递归方法。
要编译此程序,请将其保存为backup.c,然后在终端中运行以下命令:
gcc backup.c -o backup
现在你可以使用以下命令运行备份程序:
./backup <source_directory> <destination_directory>
请确保你有足够的权限来读取源目录和写入目标目录。