📄 dir.c
字号:
#include <stdio.h>
#include <dirent.h>
#include <errno.h>
#include <sys/stat.h>
#include <string.h>
#include <fcntl.h>
#include <sys/types.h>
#include <stdlib.h>
#define BUFFER_SIZE 1048576
void copy_file(char *src_path, char *dst_path)
{
void copy_dir();
int from_fd;
int to_fd;
int bytes_read;
int bytes_write;
char buffer[BUFFER_SIZE];
char *p;
if((from_fd = open(src_path, O_RDONLY)) == -1) {
fprintf(stderr, "Open %s Error:%s\n", src_path, strerror(errno));
exit(1);
}
if((to_fd = open(dst_path, O_WRONLY|O_CREAT, S_IRUSR|S_IWUSR)) == -1) {
fprintf(stderr,"Open %s Error:%s\n", dst_path, strerror(errno));
exit(1);
}
while(bytes_read = read(from_fd, buffer, BUFFER_SIZE)) {
if((bytes_read == -1) && (errno != EINTR)) {
fprintf(stderr,"read %s Error:%s\n", src_path, strerror(errno));
break;
}
else if(bytes_read > 0) {
p = buffer;
while(bytes_write = write(to_fd, p, bytes_read)) {
if((bytes_write == -1) && (errno != EINTR)) {
fprintf(stderr,"write %s Error:%s\n", dst_path, strerror(errno));
break;
}
else if(bytes_write == bytes_read)
break;
else if(bytes_write > 0) {
p += bytes_write;
bytes_read -= bytes_write;
}
}
if(bytes_write == -1) {
fprintf(stderr,"write %s Error:%s\n", dst_path, strerror(errno));
break;
}
}
}
close(from_fd);
close(to_fd);
}
void copy_dir(char *name, char *dst)
{
DIR *dp;
DIR *dp1;
char pp[255];
char pn[255];
int i;
struct stat sbuf;
struct dirent *dir;
if((dp = opendir(name)) == NULL) {
printf("Open Directory %s Error:%s\n", name, strerror(errno));
exit(1);
}
while ((dir = readdir(dp)) != NULL) {
if (dir->d_ino=0)
continue;
strcpy(pn,name);
strcat(pn,"/");
strcat(pn,dir->d_name);
strcpy(pp,dst);
strcat(pp,"/");
strcat(pp,dir->d_name);
if (lstat(pn,&sbuf) < 0) {
perror(pn);
closedir(dp);
exit(1);
}
if ( ((sbuf.st_mode & S_IFMT) != S_IFLNK) &&
((sbuf.st_mode & S_IFMT) == S_IFDIR) &&
(strcmp(dir->d_name, ".") != 0) &&
(strcmp(dir->d_name, "..") != 0) ) {
if((dp1 = opendir(pn)) == NULL) {
printf("Open Directory %s Error:%s\n",pn,strerror(errno));
exit(1);
}
if((mkdir(pp, 0700)))
break;
copy_dir(pn,pp);
}
else if ( ((sbuf.st_mode & S_IFMT) != S_IFLNK) &&
((sbuf.st_mode & S_IFMT) == S_IFREG) &&
(strcmp(dir->d_name,".") != 0) &&
(strcmp(dir->d_name, "..") != 0) ) {
copy_file(pn,pp);
}
}
}
int main(int argc,char **argv)
{
char *program_name;
DIR *dp;
struct dirent *dir;
program_name = argv[0];
if(argc != 3) {
fprintf(stderr,"Usage:%s fromdir todir\n", argv[0]);
exit(1);
}
if((dp = opendir(argv[1])) == NULL) {
printf("Open Directory %s Error:%s\n", argv[1], strerror(errno));
exit(1);
}
if((mkdir(argv[2], 0777))) {
printf("makedir %s is failed \n", argv[2]);
exit(1);
}
copy_dir(argv[1], argv[2]);
closedir(dp);
exit(0);
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -