micro-utils/coreutils/mv.c
Your Name 11b3a7907a fix
2023-11-08 19:47:09 +03:00

64 lines
1.0 KiB
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(int argc, char **argv) {
unsigned int f_flag = 0;
int opt;
while ((opt = getopt(argc, argv, "f")) != -1) {
switch (opt) {
case 'f':
f_flag = 1;
break;
default:
printf("mv [src1 src2...] [dst]\n\t[-f Force]\n");
return 0;
}
}
argv += optind;
argc -= optind;
/* Move code */
for (int i = 0; i < argc - 1; i++) {
if (rename(argv[i], argv[argc - 1]) < 0) {
if (move(argv[i], argv[argc - 1])) {
if (!f_flag)
fprintf(stderr, "mv: %s %s\n", argv[i], strerror(errno));
return 1;
}
}
}
return 0;
}