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...((...

LVL 3
aravindtjAsked:
Who is Participating?
 
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
 
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
Introducing Cloud Class® training courses

Tech changes fast. You can learn faster. That’s why we’re bringing professional training courses to Experts Exchange. With a subscription, you can access all the Cloud Class® courses to expand your education, prep for certifications, and get top-notch instructions.

 
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
 
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
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.