Skip to content

Commit ff9b215

Browse files
committed
Don't chdir()
1 parent 9db7165 commit ff9b215

File tree

1 file changed

+11
-13
lines changed

1 file changed

+11
-13
lines changed

crew-mvdir.c

Lines changed: 11 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -42,14 +42,14 @@
4242
bool verbose = false, no_clobber = false;
4343
char src[PATH_MAX], dst[PATH_MAX];
4444

45-
int move_file(const char *path, const struct stat *sb, int flag, struct FTW *ftwbuf) {
45+
int move_file(const char *src_path, const struct stat *sb, int flag, struct FTW *ftwbuf) {
4646
char dst_path[PATH_MAX] = {0};
4747
strcpy(dst_path, dst);
4848
strcat(dst_path, "/");
49-
strcat(dst_path, path);
49+
strcat(dst_path, src_path + ftwbuf->base);
5050

51-
if (strcmp(path, ".") == 0) return 0;
52-
if (verbose) fprintf(stderr, "%s%s -> %s\n", src, path, dst_path);
51+
if (strcmp(src_path, ".") == 0) return 0;
52+
if (verbose) fprintf(stderr, "%s -> %s\n", src_path, dst_path);
5353

5454
switch (flag) {
5555
case FTW_F:
@@ -65,8 +65,8 @@ int move_file(const char *path, const struct stat *sb, int flag, struct FTW *ftw
6565
}
6666

6767
// move (rename) file to dest
68-
if ( !(access(dst_path, F_OK) == 0 || rename(path, dst_path) == 0) ) {
69-
fprintf(stderr, "%s: rename() failed: %s\n", path, strerror(errno));
68+
if ( !(access(dst_path, F_OK) == 0 || rename(src_path, dst_path) == 0) ) {
69+
fprintf(stderr, "%s: rename() failed: %s\n", src_path, strerror(errno));
7070
exit(errno);
7171
}
7272

@@ -76,20 +76,20 @@ int move_file(const char *path, const struct stat *sb, int flag, struct FTW *ftw
7676
// create an identical directory in dest (with same permission) if the directory does not exist in dest
7777
if (access(dst_path, F_OK) != 0) {
7878
struct stat path_stat;
79-
stat(path, &path_stat);
79+
stat(src_path, &path_stat);
8080
mode_t dir_mode = path_stat.st_mode;
8181

8282
if (verbose) fprintf(stderr, "Creating directory %s\n", dst_path);
8383
if (mkdir(dst_path, dir_mode) != 0) {
84-
fprintf(stderr, "%s: mkdir() failed: %s\n", path, strerror(errno));
84+
fprintf(stderr, "%s: mkdir() failed: %s\n", src_path, strerror(errno));
8585
exit(errno);
8686
}
8787
}
8888

8989
break;
9090
case FTW_NS:
9191
// error
92-
fprintf(stderr, "%s: stat failed! (%s)\n", path, strerror(errno));
92+
fprintf(stderr, "%s: stat failed! (%s)\n", src_path, strerror(errno));
9393
exit(errno);
9494
}
9595
return 0;
@@ -123,13 +123,11 @@ int main(int argc, char** argv) {
123123
strcpy(src, argv[optind]);
124124
strcpy(dst, argv[optind + 1]);
125125

126-
if (chdir(src) != 0) {
126+
// call move_file() with files in src recursively
127+
if (nftw(src, move_file, 100, FTW_PHYS) != 0) {
127128
fprintf(stderr, "%s: %s\n", src, strerror(errno));
128129
exit(errno);
129130
}
130131

131-
// call move_file() with files in src recursively
132-
nftw(".", move_file, 100, FTW_PHYS);
133-
134132
return 0;
135133
}

0 commit comments

Comments
 (0)