#include #include #include #include #include #include void backup(char * olddir, char * newdir) { int r = mkdir(newdir, 0700); if (r < 0) { perror("mkdir"); exit(1); } DIR * old = opendir(olddir); struct dirent * de = readdir(old); while (de != NULL) { if (de->d_name[0] != '.') { printf("copy %s\n", de->d_name); if (de->d_type == DT_REG) { char from_name[1024], to_name[1024]; sprintf(from_name, "%s/%s", olddir, de->d_name); sprintf(to_name, "%s/%s", newdir, de->d_name); printf("copying %s to %s\n", from_name, to_name); FILE * inf = fopen(from_name, "r"); FILE * outf = fopen(to_name, "w"); while (1) { int c = fgetc(inf); if (c == EOF) break; fputc(c, outf); } fclose(inf); fclose(outf); } else if (de->d_type == DT_DIR) { char fromdir[1024], todir[1024]; sprintf(fromdir, "%s/%s", olddir, de->d_name); sprintf(todir, "%s/%s", newdir, de->d_name); printf("copying directory %s to %s\n", fromdir, todir); backup(fromdir, todir); } } de = readdir(old); } closedir(old); } int main(int argc, char * argv[]) { if (argc != 3) { fprintf(stderr, "usage %s olddir newdir\n", argv[0]); exit(1); } char * olddir = argv[1], * newdir = argv[2]; backup(olddir, newdir); }