Solved

Deleting Directory using c++ in Linux

Posted on 2004-10-29
557 Views
Last Modified: 2012-06-27
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
Question by:aravindtj
    15 Comments
     
    LVL 12

    Expert Comment

    by:stefan73
    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
     
    LVL 3

    Author Comment

    by:aravindtj
    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
     
    LVL 12

    Expert Comment

    by:stefan73
    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
     
    LVL 12

    Expert Comment

    by:stefan73
    Basically, it's like

    if(entry is directory){
        recurse into it
        rmdir()
    } else {
        unlink entry
    }
       
    0
     
    LVL 30

    Expert Comment

    by:Axter
    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
     
    LVL 39

    Expert Comment

    by:itsmeandnobodyelse
    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
     
    LVL 30

    Expert Comment

    by:Axter
    >>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
     
    LVL 39

    Expert Comment

    by:itsmeandnobodyelse
    >> there are libraries that can be used with VC++ to allow above code to compile

    Do you know where to get them?
    0
     
    LVL 30

    Expert Comment

    by:Axter
    0
     
    LVL 30

    Expert Comment

    by:Axter
    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
     
    LVL 39

    Expert Comment

    by:itsmeandnobodyelse
    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
     
    LVL 30

    Expert Comment

    by:Axter
    >>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
     
    LVL 39

    Expert Comment

    by:itsmeandnobodyelse
    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
     
    LVL 12

    Expert Comment

    by:stefan73
    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
     

    Accepted Solution

    by:
    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

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    Course: Foundations of Front-End Development

    Jump-start a lucrative career in front-end web development, with zero previous coding experience required. This course covers the basic programming concepts and languages required for creating engaging websites from scratch.

    Written by John Humphreys C++ Threading and the POSIX Library This article will cover the basic information that you need to know in order to make use of the POSIX threading library available for C and C++ on UNIX and most Linux systems.   [s…
    Introduction This article is the first in a series of articles about the C/C++ Visual Studio Express debugger.  It provides a quick start guide in using the debugger. Part 2 focuses on additional topics in breakpoints.  Lastly, Part 3 focuses on th…
    The goal of the video will be to teach the user the concept of local variables and scope. An example of a locally defined variable will be given as well as an explanation of what scope is in C++. The local variable and concept of scope will be relat…
    The viewer will learn how to user default arguments when defining functions. This method of defining functions will be contrasted with the non-default-argument of defining functions.

    845 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    10 Experts available now in Live!

    Get 1:1 Help Now