mv.c 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. /* SPDX-License-Identifier: BSD-3-Clause */
  2. /*
  3. * Copyright (C) 2022, 2023 Ferass El Hafidi <vitali64pmemail@protonmail.com>
  4. */
  5. #include <unistd.h>
  6. #include <stdio.h>
  7. #include <errno.h>
  8. #include <fcntl.h>
  9. #include <string.h>
  10. #define REQ_PRINT_USAGE /* Require print_usage() from ../common/common.h */
  11. #define REQ_ERRPRINT /* Require errprint() from ../common/common.h */
  12. #define DESCRIPTION "Move files."
  13. #define OPERANDS "[-if] source dest"
  14. #include "../common/common.h"
  15. int main(int argc, char *const argv[]) {
  16. int argument, file;
  17. char cmd, param[256], *argv0 = strdup(argv[0]);
  18. setvbuf(stdout, NULL, _IONBF, 0);
  19. for (int i = 0; i < 256; i++) param[i] = 0; /* Initialise param,
  20. * very important. */
  21. while ((argument = getopt(argc, argv, "if")) != -1) {
  22. if (argument == '?') {
  23. print_usage(argv[0], DESCRIPTION, OPERANDS, VERSION);
  24. return 1;
  25. }
  26. param[argument] = argument;
  27. if (argument == 'f') param['i'] = 0;
  28. if (argument == 'i') param['f'] = 0;
  29. } argc -= optind; argv += optind;
  30. if (!param['f']) param['i'] = 'i';
  31. if (argc < 2) {
  32. print_usage(argv0, DESCRIPTION, OPERANDS, VERSION);
  33. return 1;
  34. }
  35. if ((file = open(argv[1], O_RDONLY)) != -1 && param['i']) {
  36. printf("File exists, override it? (y/n) ");
  37. read(STDIN_FILENO, &cmd, 1);
  38. if (cmd == 'n' || cmd == 'N') {
  39. close(file);
  40. return 0;
  41. }
  42. }
  43. close(file); /* In case it hasn't been closed */
  44. if (rename(argv[0], argv[1]))
  45. /* Technically, moving files == renaming files */
  46. return errprint(argv0, NULL, errno);
  47. return 0;
  48. }