Removing a non empty directory programmatically in C or C++

后端 未结 8 2461
一生所求
一生所求 2020-11-27 16:50

How to delete a non empty directory in C or C++? Is there any function? rmdir only deletes empty directory. Please provide a way without using any external library.

8条回答
  •  难免孤独
    2020-11-27 17:19

    //======================================================
    // Recursely Delete files using:
    //   Gnome-Glib & C++11
    //======================================================
    
    #include 
    #include 
    #include 
    #include 
    
    using namespace std;
    
    int DirDelete(const string& path)
    {
       const gchar*    p;
       GError*   gerr;
       GDir*     d;
       int       r;
       string    ps;
       string    path_i;
       cout << "open:" << path << "\n";
       d        = g_dir_open(path.c_str(), 0, &gerr);
       r        = -1;
    
       if (d) {
          r = 0;
    
          while (!r && (p=g_dir_read_name(d))) {
              ps = string{p};
              if (ps == "." || ps == "..") {
                continue;
              }
    
              path_i = path + string{"/"} + p;
    
    
              if (g_file_test(path_i.c_str(), G_FILE_TEST_IS_DIR) != 0) {
                cout << "recurse:" << path_i << "\n";
                r = DirDelete(path_i);
              }
              else {
                cout << "unlink:" << path_i << "\n";
                r = g_unlink(path_i.c_str());
              }
          }
    
          g_dir_close(d);
       }
    
       if (r == 0) {
          r = g_rmdir(path.c_str());
         cout << "rmdir:" << path << "\n";
    
       }
    
       return r;
    }
    

提交回复
热议问题