在 C 或 C 中以编程方式删除非空目录

新手上路,请多包涵

如何删除 C 或 C++ 中的非空目录?有什么功能吗? rmdir 只删除空目录。请提供一种不使用任何外部库的方法。

还告诉我如何删除 C 或 C++ 中的文件?

原文由 avd 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.4k
2 个回答

您想编写一个函数(递归函数最简单,但在深层目录上很容易耗尽堆栈空间),它将枚举目录的子级。如果你发现一个子目录是一个目录,你就递归它。否则,你删除里面的文件。完成后,目录为空,您可以通过系统调用将其删除。

要枚举 Unix 上的目录,您可以使用 opendir()readdir()closedir() 。要删除您,请在空目录上使用 rmdir() (即在您的函数结束时,在删除子目录后)和 unlink() 在文件上。请注意,在许多系统上,不支持 d_type 中的成员 struct dirent ;在这些平台上,您必须使用 stat()S_ISDIR(stat.st_mode) 来确定给定路径是否为目录。

On Windows, you will use FindFirstFile() / FindNextFile() to enumerate, RemoveDirectory() on empty directories, and DeleteFile() to remove files.

这是一个可能适用于 Unix 的示例(完全未经测试):

 int remove_directory(const char *path) {
   DIR *d = opendir(path);
   size_t path_len = strlen(path);
   int r = -1;

   if (d) {
      struct dirent *p;

      r = 0;
      while (!r && (p=readdir(d))) {
          int r2 = -1;
          char *buf;
          size_t len;

          /* Skip the names "." and ".." as we don't want to recurse on them. */
          if (!strcmp(p->d_name, ".") || !strcmp(p->d_name, ".."))
             continue;

          len = path_len + strlen(p->d_name) + 2;
          buf = malloc(len);

          if (buf) {
             struct stat statbuf;

             snprintf(buf, len, "%s/%s", path, p->d_name);
             if (!stat(buf, &statbuf)) {
                if (S_ISDIR(statbuf.st_mode))
                   r2 = remove_directory(buf);
                else
                   r2 = unlink(buf);
             }
             free(buf);
          }
          r = r2;
      }
      closedir(d);
   }

   if (!r)
      r = rmdir(path);

   return r;
}

原文由 asveikau 发布,翻译遵循 CC BY-SA 4.0 许可协议

此代码将打开特定目录并遍历所有文件并删除该目录下的文件。之后它将在最后删除空目录。

 /**
 * @file RemoveDir.c
 * @author Om Patel (ompatel1861@gmail.com)
 * @brief This program will remove non empty directory.
 * @version 0.1
 * @date 2022-05-31
 *
 * @copyright Copyright (c) 2022
 *
 */

#include<stdio.h>
#include<string.h>
#include<dirent.h>
#include <unistd.h>

int main()
{
    DIR* dir = opendir("OUTPUT/Aakash");
    struct dirent* entity;
    entity = readdir(dir);
    while(entity != NULL){
        char path[30] ="OUTPUT/Aakash/";
        printf("%s\n",entity->d_name);
        strcat(path,entity->d_name);
        printf("PAth: %s\n",path);
        remove(path);
        entity = readdir(dir);
    }
    char path1[30] ="OUTPUT/Aakash";
    rmdir(path1);
    closedir(dir);
    char out[20]="OUTPUT/";
                char fol_file[30];
            sprintf(fol_file,"%s\\",out);
            printf("%s",fol_file);
    return 0;
}

原文由 OM PATEL 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题