在Debian系统中,使用readdir
函数可以帮助你遍历目录并获取目录中的文件列表。为了实现文件备份,你可以编写一个简单的C程序来读取源目录中的所有文件,并将它们复制到目标目录中。以下是一个基本的示例代码,展示了如何使用readdir
和shutil
库来实现文件备份:
#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 *dest) {
FILE *src_file = fopen(src, "rb");
FILE *dest_file = fopen(dest, "wb");
if (src_file == NULL || dest_file == NULL) {
perror("Error opening file");
return;
}
char buffer[1024];
size_t bytes_read;
while ((bytes_read = fread(buffer, 1, sizeof(buffer), src_file)) > 0) {
fwrite(buffer, 1, bytes_read, dest_file);
}
fclose(src_file);
fclose(dest_file);
}
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 *dest_dir = argv[2];
struct dirent *entry;
DIR *dp = opendir(src_dir);
if (dp == NULL) {
perror("opendir");
return 1;
}
while ((entry = readdir(dp)) != NULL) {
if (entry->d_type == DT_REG) { // Only regular files
char src_path[1024], dest_path[1024];
snprintf(src_path, sizeof(src_path), "%s/%s", src_dir, entry->d_name);
snprintf(dest_path, sizeof(dest_path), "%s/%s", dest_dir, entry->d_name);
// Ensure the destination directory exists
struct stat st = {0};
if (stat(dest_dir, &st) == -1) {
mkdir(dest_dir, 0755);
}
backup_file(src_path, dest_path);
}
}
closedir(dp);
return 0;
}
backup.c
。backup.c
的目录。gcc -o backup backup.c
./backup /path/to/source /path/to/destination
通过这种方式,你可以使用Debian系统中的readdir
函数来实现文件备份。