2 Copyright © 2013 Alastair Stuart
4 This program is open source software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation, either version 3 of the License, or
7 (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
24 #define VERSION "0.01"
26 void usage(char* program
)
28 printf("Usage: %s [options] [source ...] [dest]\n", program
);
29 printf("Moves files.\n"
31 " --help Print this message.\n"
32 " --version Show version info.\n");
35 int main(int argc
, char* argv
[])
37 static struct option long_options
[] = {
38 {"help", no_argument
, NULL
, 1},
39 {"version", no_argument
, NULL
, 2},
44 while ((c
= getopt_long(argc
, argv
, "",
45 long_options
, NULL
)) != -1)
53 printf("mv (mutos) v"VERSION
"\n");
56 fprintf(stderr
,"Run '%s --help' for usage.\n",
62 if ((argc
- optind
) == 0) {
63 fprintf(stderr
, "%s: Missing operands\n"
64 "Run '%s --help' for usage.\n",
67 } else if ((argc
- optind
) == 1) {
69 fprintf(stderr
, "%s: Missing destination operand\n"
70 "Run '%s --help' for usage.\n",
77 char* dest_path
= argv
[argc
- 1];
78 bool dest_dir
= false;
81 int rc
= stat(dest_path
, &dest
);
83 // if destination is a directory
84 if (dest
.st_mode
& S_IFDIR
) {
87 // if multiple source files are specified
88 // and dest isn't a directory
90 fprintf(stderr
, "%s: Destination is not a directory: %s\n",
97 for (int i
= 1; i
< argc
- 1; i
++)
100 // concat dest path and filename
101 size_t dest_len
= strlen(dest_path
) + 1 + strlen(argv
[i
]) + 1;
102 char* dest
= calloc(1, dest_len
);
104 fprintf(stderr
, "%s: %s: %s",
105 argv
[0], strerror(errno
), argv
[i
]);
109 strncat(dest
, dest_path
, dest_len
- strlen(dest
) - 1);
110 strncat(dest
, "/", dest_len
- strlen(dest
) - 1);
111 strncat(dest
, argv
[i
], dest_len
- strlen(dest
) - 1);
112 dest
[dest_len
- 1] = '\0';
114 rc
= rename(argv
[i
], dest
);
116 fprintf(stderr
, "%s: %s: %s\n",
117 argv
[0], strerror(errno
), argv
[i
]);
123 rc
= rename(argv
[i
], dest_path
);
125 fprintf(stderr
, "%s: %s: %s\n",
126 argv
[0], strerror(errno
), argv
[i
]);