通过readdir函数可读取目录内容。借助遍历源目录全部文件与子目录并复制至目标位置,能实现文件备份。下文展示一个具体示例。

#include <stdio.h>#include <stdlib.h>#include <string.h>#include <dirent.h>#include <sys/stat.h>#include <unistd.h>#include <sys/stat.h>#include <fcntl.h>void backup_file(const char *src, const char *dst) {int src_fd = open(src, O_RDONLY);int dst_fd = open(dst, O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR);if (src_fd == -1 || dst_fd == -1) {perror("open");return;}char buffer[4096];ssize_t bytes_read, bytes_written;while ((bytes_read = read(src_fd, buffer, sizeof(buffer))) > 0) {bytes_written = write(dst_fd, buffer, bytes_read);if (bytes_written != bytes_read) {perror("write");break;}}close(src_fd);close(dst_fd);}void backup_directory(const char *src, const char *dst) {char src_path[1024], dst_path[1024];struct dirent *entry;DIR *dp = opendir(src);if (!dp) {perror("opendir");return;}while ((entry = readdir(dp)) != 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);struct stat st;if (stat(src_path, &st) == -1) {perror("stat");continue;}if (S_ISDIR(st.st_mode)) {mkdir(dst_path, st.st_mode);backup_directory(src_path, dst_path);} else {backup_file(src_path, dst_path);}}closedir(dp);}int main(int argc, char *argv[]) {if (argc != 3) {printf("Usage: %s <source_directory> <destination_directory>n", argv[0]);return 1;}const char *src = argv[1];const char *dst = argv[2];if (mkdir(dst, 0755) == -1 && errno != EEXIST) {perror("mkdir");return 1;}backup_directory(src, dst);return 0;}该程序利用两个命令行参数指定源与目标目录,递归复制所有文件。需注意它不处理符号链接或设备文件等特殊类型,可根据实际需求扩展功能。