Advertisement
Guest User

Untitled

a guest
Aug 25th, 2019
117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.51 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <sys/stat.h>
  3.  
  4. #include <string.h>
  5. #include <ftw.h>
  6.  
  7. #include <stdlib.h>
  8.  
  9. void usage()
  10. {
  11. printf("usage: rm [-r] file");
  12. }
  13.  
  14. short is_directory(char *path)
  15. {
  16. struct stat path_stat;
  17. stat(path, &path_stat);
  18.  
  19. return S_ISREG(path_stat.st_mode);
  20. }
  21.  
  22. short remove_file(char *argv)
  23. {
  24. struct stat file = {0};
  25.  
  26. if (stat(argv, &file) == -1) /* check if file exists */
  27. printf("%s doesn't exist\n", argv);
  28.  
  29. else if (is_directory(argv) == 0) /* check if file is a directory */
  30. printf("%s is a directory\n", argv);
  31.  
  32. else {
  33. remove(argv);
  34. }
  35.  
  36. return 0;
  37. }
  38.  
  39. static int rmFiles(const char *pathname, const struct stat *sbuf, int type, struct FTW *ftwb)
  40. {
  41. if (remove(pathname) < 0) {
  42. perror("ERROR: remove");
  43. return -1;
  44. }
  45.  
  46. return 0;
  47. }
  48.  
  49. short removedir(char *rdir)
  50. {
  51. if (nftw(&rdir[0], rmFiles, 10, FTW_DEPTH|FTW_MOUNT|FTW_PHYS) < 0) {
  52. perror("ERROR: ntfw");
  53. exit(1);
  54. }
  55.  
  56. return 0;
  57. }
  58.  
  59. int main(int argc, char *argv[])
  60. {
  61. short i;
  62.  
  63. if (argc < 2)
  64. usage();
  65.  
  66. for (i = 1; i < argc; i++) {
  67. if (strncmp(argv[1], "-r", 2) == 0) {
  68. removedir(argv[i]);
  69. }
  70.  
  71. else
  72. remove_file(argv[i]);
  73. }
  74.  
  75. return 0;
  76. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement