在 CentOS 系统中,你可以使用 readdir 函数来读取目录中的文件和子目录。但是,readdir 本身并不直接实现文件复制功能。要实现文件复制,你可以结合 readdir 和其他文件操作函数,如 fopen、fread、fwrite 和 fclose。以下是一个简单的示例,展示了如何使用这些函数来复制目录中的所有文件:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
void copy_file(const char *src, const char *dst) {
int src_fd = open(src, O_RDONLY);
if (src_fd == -1) {
perror("open source file");
return;
}
int dst_fd = open(dst, O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR);
if (dst_fd == -1) {
perror("open destination file");
close(src_fd);
return;
}
char buffer[1024];
ssize_t n;
while ((n = read(src_fd, buffer, sizeof(buffer))) > 0) {
if (write(dst_fd, buffer, n) != n) {
perror("write");
break;
}
}
if (n == -1) {
perror("read");
}
close(src_fd);
close(dst_fd);
}
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];
DIR *dir = opendir(src_dir);
if (!dir) {
perror("opendir");
return 1;
}
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
if (entry->d_type == DT_REG) { // Only copy regular files
char src_path[PATH_MAX];
char 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);
copy_file(src_path, dst_path);
}
}
closedir(dir);
return 0;
}
这个程序接受两个命令行参数:源目录和目标目录。它将遍历源目录中的所有文件(不包括子目录),并将它们复制到目标目录。注意,这个示例仅适用于复制普通文件,不包括子目录和其他特殊文件类型。
要编译此程序,请将其保存为 copy_files.c,然后在终端中运行以下命令:
gcc -o copy_files copy_files.c
现在你可以使用以下命令运行程序,将源目录中的所有文件复制到目标目录:
./copy_files /path/to/source_directory /path/to/destination_directory