Ubuntu c++ 删除文件夹或者文件

╰+攻爆jí腚メ 2022-04-24 02:36 748阅读 0赞

废话不多说,以下代码中在Remove方法中传入文件路径即可.

  1. //Recursively delete all the file in the directory.
  2. int rm_dir(std::string dir_full_path) {
  3. DIR* dirp = opendir(dir_full_path.c_str());
  4. if(!dirp)
  5. {
  6. return -1;
  7. }
  8. struct dirent *dir;
  9. struct stat st;
  10. while((dir = readdir(dirp)) != NULL)
  11. {
  12. if(strcmp(dir->d_name,".") == 0
  13. || strcmp(dir->d_name,"..") == 0)
  14. {
  15. continue;
  16. }
  17. std::string sub_path = dir_full_path + '/' + dir->d_name;
  18. if(lstat(sub_path.c_str(),&st) == -1)
  19. {
  20. //Log("rm_dir:lstat ",sub_path," error");
  21. continue;
  22. }
  23. if(S_ISDIR(st.st_mode))
  24. {
  25. if(rm_dir(sub_path) == -1) // 如果是目录文件,递归删除
  26. {
  27. closedir(dirp);
  28. return -1;
  29. }
  30. rmdir(sub_path.c_str());
  31. }
  32. else if(S_ISREG(st.st_mode))
  33. {
  34. unlink(sub_path.c_str()); // 如果是普通文件,则unlink
  35. }
  36. else
  37. {
  38. //Log("rm_dir:st_mode ",sub_path," error");
  39. continue;
  40. }
  41. }
  42. if(rmdir(dir_full_path.c_str()) == -1)//delete dir itself.
  43. {
  44. closedir(dirp);
  45. return -1;
  46. }
  47. closedir(dirp);
  48. return 0;
  49. }
  50. //Remove files or dirs
  51. bool Remove(std::string file_name) {
  52. std::string file_path = file_name;
  53. struct stat st;
  54. if (lstat(file_path.c_str(),&st) == -1) {
  55. return EXIT_FAILURE;
  56. }
  57. if (S_ISREG(st.st_mode)) {
  58. if (unlink(file_path.c_str()) == -1) {
  59. return EXIT_FAILURE;
  60. }
  61. }
  62. else if(S_ISDIR(st.st_mode)) {
  63. if(file_name == "." || file_name == "..") {
  64. return EXIT_FAILURE;
  65. }
  66. if(rm_dir(file_path) == -1)//delete all the files in dir.
  67. {
  68. return EXIT_FAILURE;
  69. }
  70. }
  71. return EXIT_SUCCESS;
  72. }

发表评论

表情:
评论列表 (有 0 条评论,748人围观)

还没有评论,来说两句吧...

相关阅读