rm.c 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. /* vim: tabstop=4 shiftwidth=4 noexpandtab
  2. * This file is part of ToaruOS and is released under the terms
  3. * of the NCSA / University of Illinois License - see LICENSE.md
  4. * Copyright (C) 2013-2018 K. Lange
  5. *
  6. * rm - Unlink files
  7. *
  8. * TODO: Support recursive, directory removal, etc.
  9. */
  10. #include <stdio.h>
  11. #include <string.h>
  12. #include <unistd.h>
  13. #include <errno.h>
  14. #include <dirent.h>
  15. #include <fcntl.h>
  16. #include <sys/stat.h>
  17. #include <sys/ioctl.h>
  18. static int recursive = 0;
  19. static int rm_thing(char * tmp);
  20. static int rm_directory(char * source) {
  21. DIR * dirp = opendir(source);
  22. if (dirp == NULL) {
  23. fprintf(stderr, "could not open %s\n", source);
  24. return 1;
  25. }
  26. struct dirent * ent = readdir(dirp);
  27. while (ent != NULL) {
  28. if (!strcmp(ent->d_name,".") || !strcmp(ent->d_name,"..")) {
  29. ent = readdir(dirp);
  30. continue;
  31. }
  32. char tmp[strlen(source)+strlen(ent->d_name)+2];
  33. sprintf(tmp, "%s/%s", source, ent->d_name);
  34. int status = rm_thing(tmp);
  35. if (status) return status;
  36. ent = readdir(dirp);
  37. }
  38. closedir(dirp);
  39. return unlink(source);
  40. }
  41. static int rm_thing(char * tmp) {
  42. struct stat statbuf;
  43. lstat(tmp,&statbuf);
  44. if (S_ISDIR(statbuf.st_mode)) {
  45. if (!recursive) {
  46. fprintf(stderr, "rm: %s: is a directory\n", tmp);
  47. return 1;
  48. }
  49. return rm_directory(tmp);
  50. } else {
  51. return unlink(tmp);
  52. }
  53. }
  54. int main(int argc, char * argv[]) {
  55. int opt;
  56. while ((opt = getopt(argc, argv, "r")) != -1) {
  57. switch (opt) {
  58. case 'r':
  59. recursive = 1;
  60. break;
  61. default:
  62. fprintf(stderr, "rm: unrecognized option '%c'\n", opt);
  63. break;
  64. }
  65. }
  66. int ret = 0;
  67. for (int i = optind; i < argc; ++i) {
  68. ret |= rm_thing(argv[i]);
  69. }
  70. return ret;
  71. }