57 lines
978 B
C
57 lines
978 B
C
#include <stdio.h>
|
|
#include <errno.h>
|
|
#include <fcntl.h>
|
|
#include <libgen.h>
|
|
#include <string.h>
|
|
#include <stdlib.h>
|
|
#include <unistd.h>
|
|
|
|
int move(const char *src, const char *dst) {
|
|
char *copy = strdup(src);
|
|
if (!copy)
|
|
return 1;
|
|
|
|
char *bname = basename(copy);
|
|
|
|
size_t len = strlen(dst) + strlen(bname) + 2;
|
|
char *new_path = malloc(len + 1);
|
|
if (!new_path)
|
|
return 1;
|
|
|
|
snprintf(new_path, len, "%s/%s", dst, bname);
|
|
|
|
int ret = 0;
|
|
if (rename(src, new_path) < 0)
|
|
ret = 1;
|
|
|
|
free(new_path);
|
|
free(copy);
|
|
|
|
return ret;
|
|
}
|
|
|
|
int main(const int argc, const char **argv) {
|
|
if (argc == 2) {
|
|
printf("mv: missing operand\n");
|
|
return 1;
|
|
}
|
|
|
|
else if (argc == 3) {
|
|
if (rename(argv[1], argv[2]) < 0) {
|
|
fprintf(stderr, "mv: %s %s\n", argv[1], strerror(errno));
|
|
return 1;
|
|
}
|
|
}
|
|
|
|
else {
|
|
for (int i = 1; i < argc - 1; i++) {
|
|
if (move(argv[i], argv[argc - 1])) {
|
|
fprintf(stderr, "mv: %s %s\n", argv[i], strerror(errno));
|
|
return 1;
|
|
}
|
|
}
|
|
}
|
|
|
|
return 0;
|
|
}
|