micro-utils/coreutils/mv.c
2023-11-07 16:21:46 +03:00

48 lines
849 B
C

#include <stdio.h>
#include <errno.h>
#include <fcntl.h>
#include <libgen.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include "make_path.h"
int move(const char *src, const char *dst) {
char *copy = strdup(src);
if (!copy)
return 1;
char *new_path = mu_make_path("mv", dst, basename(copy));
if (new_path == NULL) {
free(copy);
return 1;
}
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 || argv[argc - 1][0] == '-') {
printf("mv [src1 src2...] [dst]\n");
return 0;
}
for (int i = 1; i < argc - 1; i++) {
if (rename(argv[i], argv[argc - 1]) < 0) {
if (move(argv[i], argv[argc - 1])) {
fprintf(stderr, "mv: %s %s\n", argv[i], strerror(errno));
return 1;
}
}
}
return 0;
}