#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <unistd.h>
#include <fcntl.h>
#include <dirent.h>
#include <utime.h>
#define BUF_SIZE 1024
#define MAX_PATH 256
void changeTimeAndP(char* path, struct stat* buf) {
int res;
if (S_ISLNK(buf->st_mode)) {
struct timeval times[2];
times[0].tv_sec = buf->st_atime;
times[0].tv_usec = 0;
times[1].tv_sec = buf->st_mtime;
times[1].tv_usec = 0;
res = lutimes(path, times);
} else {
struct timeval times[2];
times[0].tv_sec = buf->st_atime;
times[0].tv_usec = 0;
times[1].tv_sec = buf->st_mtime;
times[1].tv_usec = 0;
res = utimes(path, times);
}
chmod(path, buf->st_mode);
chown(path, buf->st_uid, buf->st_gid);
}
void cp(char* src, char* dst, mode_t mode) {
char buf[BUF_SIZE];
int srcid = open(src, O_RDONLY);
int dstid = creat(dst, mode);
int bytesize = 1;
while ((bytesize = read(srcid, buf, BUF_SIZE)) > 0) {
write(dstid, buf, bytesize);
memset(buf, 0, sizeof(buf));
}
printf("%s -> %s\n", src, dst);
close(srcid);
close(dstid);
}
int is_current(const char* path) {
return path[0] == '.' && path[1] == '/';
}
int is_parent(const char* path) {
return path[0] == '.' && path[1] == '.' && path[2] == '/';
}
void get_real_link(char* src, char* link, int first = 1) {
if (is_current(link)) {
if (first) {
*(strrchr(src, '/')) = 0;
}
link += 2;
} else if (is_parent(link)) {
if (first) {
*(strrchr(src, '/')) = 0;
}
*(strrchr(src, '/')) = 0;
link += 3;
} else {
strcat(src, "/");
strcat(src, link);
return;
}
get_real_link(src, link, 0);
return;
}
int cplink(char* src, char* dst) {
char buf[BUF_SIZE] = "";
char absolute[PATH_MAX];
readlink(src, buf, sizeof(buf));
buf[strlen(buf)] = 0;
printf("src: %s, link: %s\n", src, buf);
get_real_link(src, buf);
printf("src: %s\n", src);
realpath(src, absolute);
printf("%s\n", absolute);
int res = symlink(absolute, dst);
return res;
}
int copyDir(char* srcDir, char* dstDir) {
struct stat statbuf;
struct dirent* entry;
DIR* dp;
if ((dp = opendir(srcDir)) == NULL) {
printf("opendir error.\n");
return -1;
}
entry = readdir(dp);
lstat(srcDir, &statbuf);
mkdir(dstDir, statbuf.st_mode);
do {
char src[MAX_PATH];
strcpy(src, srcDir);
strcat(src, "/");
strcat(src, entry->d_name);
char dst[MAX_PATH];
strcpy(dst, dstDir);
strcat(dst, "/");
strcat(dst, entry->d_name);
lstat(src, &statbuf);
if (S_ISDIR(statbuf.st_mode)) {
if (strcmp(entry->d_name, ".") == 0 ||
strcmp(entry->d_name, "..") == 0)
continue;
copyDir(src, dst);
} else if (S_ISLNK(statbuf.st_mode)) {
cplink(src, dst);
} else if (S_ISREG(statbuf.st_mode)) {
cp(src, dst, statbuf.st_mode);
}
changeTimeAndP(dst, &statbuf);
} while (entry = readdir(dp));
}
int main(int argc, char* argv[]) {
if (argc < 3) {
printf("usage锛歮ycp path1 path2\n");
return -1;
}
printf("src: %s tgt :%s\n", argv[1], argv[2]);
printf("begin\n");
copyDir(argv[1], argv[2]);
printf("finish\n");
return 0;
}
2020-12-25
最新推荐文章于 2022-05-28 23:38:12 发布