[Webinar] Streamline your web hosting managementRegister Today

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 564
  • Last Modified:

Deleting Directory using c++ in Linux

How can i delete a directory(/home/user/projects/temporaryfiles) which contains files and folders using c++ in Linux?
And I have to do this one with out any system() function calls...((...

0
aravindtj
Asked:
aravindtj
  • 5
  • 4
  • 4
  • +2
1 Solution
 
stefan73Commented:
Hi aravindtj,
Normally, you'd do that with rm -rf, but as you don't, I assume it's homework.

You need opendir(), readdir(), closedir(), stat(), rmdir(), unlink() and eventually glob(). It's recursive.



Cheers!

Stefan
0
 
aravindtjAuthor Commented:
hi stefan73,
 Thanks for you reply, with rmdir() i can delete only the empty directories, but here i need to delete the non empty folder.
0
 
stefan73Commented:
aravindtj,
Right. That's why you need to recurse into the directories first, deleting files on the way. Check this link for a simple recursion example:

http://www.experts-exchange.com/Programming/Programming_Platforms/Unix_Programming/Q_21164637.html#12284568
0
The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

 
stefan73Commented:
Basically, it's like

if(entry is directory){
    recurse into it
    rmdir()
} else {
    unlink entry
}
   
0
 
AxterCommented:
Why not just use rm command in a system call?

Examples:
system("rm -rf dirname");
system("rm -rf \home\dirname");
system("rm -rf ~\dirname");
0
 
itsmeandnobodyelseCommented:
Stefan's suggestion should be similar to that below, though it doesn't compile on my Windows platform ;-)

#include <stdio.h>
#include <sys/stat.h>
#include <sys/dir.h>
#include <dirent.h>

void deldir(const char* szDir)
{
    DIR *d;
    struct dirent *de;
   
    if (!(d = opendir(szDir)))
    {
        cout << "Can't open directory " << szDir << endl;
        return;
    }

    while ((de = readdir(d)))
    {
        struct stat fs;
        if (stat(de->d_name, &fs) != 0)
        {
            cout << "Couldn't get stat of " << de->d_name << endl;
            return;
        }

        if ((fs.st_mode & S_IFDIR) != 0)
            deldir(de->d_name);
        else
            remove(de->d_name);

   }

    closedir(d);
}

Regards, Alex
 
0
 
AxterCommented:
>>though it doesn't compile on my Windows platform ;-)

weather or not the above code compiles has nothing to do with the platform.

The above code will compile on compilers that support POSIX type search file functions.
The Borland compiler should be able to compile above code in Windows platform.

VC++ does not support opendir POSIX functions, so above code will not compile in VC++, although there are libraries that can be used with VC++ to allow above code to compile.
0
 
itsmeandnobodyelseCommented:
>> there are libraries that can be used with VC++ to allow above code to compile

Do you know where to get them?
0
 
AxterCommented:
0
 
AxterCommented:
OT FYI:

Windows claims to be in compliance with the POSIX standard.
However, unlike all other platforms that make this claim, Windows does not include API functions for the POSIX standard.

I've been told that MS only made Windows POSIX compliance so that they could obtain government contracts.
0
 
itsmeandnobodyelseCommented:
Thanks, the first link had valid code dirent.h and dirent.c (the second had a header file only, the third w95 special code that i didn't try).

The deldir function compiles and runs. However, i have to exclude  "." and ".." sub-directories.

Regards, Alex



 
0
 
AxterCommented:
>>The deldir function compiles and runs. However, i have to exclude  "." and ".." sub-directories.

You could probably modify the source code so that deldir would ignore "." and ".."

0
 
itsmeandnobodyelseCommented:
That's the final code tested with VC++ 6.0 and NT 4.0

#include <iostream>
using namespace std;

#include <stdio.h>
#include <sys/stat.h>
#include <direct.h>
#include <errno.h>
#include "dirent.h"  // www.two-sdg.demon.co.uk/curbralan/code/dirent/dirent.html

void deldir(const char* szDir)
{
    DIR *d;
    struct dirent *de;
   
    if (!(d = opendir(szDir)))
    {
        cout << "Can't clean files from directory " << szDir << " errno=" << errno << endl;
        return;
    }
    char szCurDir[256];
    getcwd(szCurDir, 256);
    chdir(szDir);
    while ((de = readdir(d)))
    {
        struct stat fs;
        if (stat(de->d_name, &fs) != 0)
        {
            cout << "Couldn't get stat of " << de->d_name << " errno=" << errno << endl;
            return;
        }

        if ((fs.st_mode & S_IFDIR) != 0)
        {
            if (de->d_name[0] != '.')
               deldir(de->d_name);
        }
        else
            remove(de->d_name);

   }

    closedir(d);
    chdir(szCurDir);
}

int main(int nArg, char* pszArgs[])
{
    if (nArg == 2)
        deldir(pszArgs[1]);
    return 0;
}

0
 
stefan73Commented:
itsmeandnobodyelse,
>   if (de->d_name[0] != '.')

Careful: Although you cannot create directories starting with "." using explorer on NT4, it's possible to do so with the command line or with CygWin. Better do a double strcmp for "." and "..".

And I don't see you deleting the directory itself. This should be done last after the chdir() call. Check if a path buffer of 256 bytes is sufficient for deep directory trees - maybe it isn't.
0
 
ArulPrabhuTCommented:
hi aravindtj,
       you are just looking for to delete a non-empty directory in linux, here is the code snippet just try with this one.

bool DirectoryDelete(const char* dirPath)
{
    DIR *dir;
    struct dirent *entry;
    char path[PATH_MAX];

if (path == NULL)
{

      cout << "Error while deleting directory\n";
        return false;
    }
    dir = opendir(dirPath);
    if (dir == NULL)
      {
            cout << "Error in openning directory\n";
        return false;
    }

      bool recursiveReturnValue;

    while ((entry = readdir(dir)) != NULL)
      {
        if (strcmp(entry->d_name, ".") && strcmp(entry->d_name, ".."))
            {
            snprintf(path, (size_t) PATH_MAX, "%s/%s", dirPath, entry->d_name);
                  
            if (entry->d_type == DT_DIR)
                  {
                recursiveReturnValue = this->DeleteDirectory(path);
            }
                  remove(path);
        }

    }
    closedir(dir);
      
      if (remove(dirPath) == 0)
            return true;
      else
            return false;
}
0

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 5
  • 4
  • 4
  • +2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now