用C语言实现对一个目录进行拷贝,不考虑目录下还有目录的情况
时间: 2024-02-18 11:04:32 浏览: 24
好的,以下是一个简单的用C语言实现对一个目录进行拷贝的代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <sys/stat.h>
void copy_file(const char *src, const char *dst) {
FILE *fp_src, *fp_dst;
char buffer[1024];
size_t n;
if ((fp_src = fopen(src, "rb")) == NULL) {
perror("fopen");
exit(EXIT_FAILURE);
}
if ((fp_dst = fopen(dst, "wb")) == NULL) {
perror("fopen");
exit(EXIT_FAILURE);
}
while ((n = fread(buffer, 1, sizeof(buffer), fp_src)) > 0) {
if (fwrite(buffer, 1, n, fp_dst) != n) {
perror("fwrite");
exit(EXIT_FAILURE);
}
}
fclose(fp_src);
fclose(fp_dst);
}
void copy_dir(const char *src, const char *dst) {
DIR *dir;
struct dirent *entry;
struct stat statbuf;
char src_path[1024], dst_path[1024];
if ((dir = opendir(src)) == NULL) {
perror("opendir");
exit(EXIT_FAILURE);
}
while ((entry = readdir(dir)) != 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);
if (lstat(src_path, &statbuf) < 0) {
perror("lstat");
exit(EXIT_FAILURE);
}
if (S_ISREG(statbuf.st_mode)) {
copy_file(src_path, dst_path);
}
}
closedir(dir);
}
int main(int argc, char *argv[]) {
if (argc != 3) {
fprintf(stderr, "Usage: %s <src_dir> <dst_dir>\n", argv[0]);
exit(EXIT_FAILURE);
}
copy_dir(argv[1], argv[2]);
return 0;
}
```
这个程序可以接受两个参数,第一个参数是源目录的路径,第二个参数是目标目录的路径。程序首先打开源目录,然后遍历目录中的所有文件和子目录,如果是文件就进行拷贝,如果是子目录则跳过。在拷贝文件的时候,程序使用了标准的文件读写操作,将源文件的内容读入缓冲区中,然后将缓冲区的内容写入目标文件中。