LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Deleting a Directory using c++ in Linux (https://www.linuxquestions.org/questions/programming-9/deleting-a-directory-using-c-in-linux-248696/)

ArulPrabhuT 10-29-2004 06:12 AM

Deleting a Directory using c++ in Linux
 
I want to delete a directory(which contains files and subfolders) using c++ in Linux, is there any solution to do this one?

any help would be appreciated.

Hko 10-29-2004 07:36 AM

Re: Deleting a Directory using c++ in Linux
 
Quote:

Originally posted by ArulPrabhuT
I want to delete a directory(which contains files and subfolders) using c++ in Linux, is there any solution to do this one?
Of course you could do somthing like:
Code:

#include <stdlib.h>
/* ... */
system("rm -r /your/directory");

But then not your program is doing the deletion: you call the "rm" program from you own program.

To really do this in C/C++ your actually need to walk the entire directory tree, deleting all files and then the directory itself. And when there's sub directory inside it, you first need to do the same with that directory.

Here's a recursive program that does this. It's in C, but should work in C++.
Please be carefull! It is at least as dangerous as "rm -rf"
I did not test this thourougly, and I don't take responsibility for any data deleted by it. Test it yourself until confident before including the actual deletion code.
Code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#include <sys/types.h>
#include <unistd.h>
#include <dirent.h>

int removedirectoryrecursively(const char *dirname)
{
    DIR *dir;
    struct dirent *entry;
    char path[PATH_MAX];

    if (path == NULL) {
        fprintf(stderr, "Out of memory error\n");
        return 0;
    }
    dir = opendir(dirname);
    if (dir == NULL) {
        perror("Error opendir()");
        return 0;
    }

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

            /*
            * Here, the actual deletion must be done.  Beacuse this is
            * quite a dangerous thing to do, and this program is not very
            * well tested, we are just printing as if we are deleting.
            */
            printf("(not really) Deleting: %s\n", path);
            /*
            * When you are finished testing this and feel you are ready to do the real
            * deleting, use this: remove*STUB*(path);
            * (see "man 3 remove")
            * Please note that I DONT TAKE RESPONSIBILITY for data you delete with this!
            */
        }

    }
    closedir(dir);

    /*
    * Now the directory is emtpy, finally delete the directory itself. (Just
    * printing here, see above)
    */
    printf("(not really) Deleting: %s\n", dirname);

    return 1;
}


int main(int argc, char *argv[])
{
    char answer[10];
    int yes, no;

    if (argc != 2) {
        fprintf(stderr, "Usage:\t%s <directory>\n", *argv);
        return 1;
    }
    do {
        printf("\nAre you sure you want to delete the entire directory %s?\n",
              argv[1]);
        fgets(answer, 5, stdin);
        yes = !strncmp(answer, "yes\n", 4);
        no = !strncmp(answer, "no\n", 3);
        if (no) {
            printf("\nexit...\n");
            return 0;
        } else if (yes) {
            /*
            * Start deleting the directory...
            */
            return !removedirectoryrecursively(argv[1]);
        } else {
            printf("\nPlease answer exactly yes or no.");
        }
    } while (!yes && !no);
    return 0;
}


ArulPrabhuT 11-01-2004 08:00 AM

Thanks Hko
thanks for the solution with this example i managed to delete the non-empty directory.

Hko 11-01-2004 10:44 AM

Oh yes,... If you use the code above, please remove this part below. It was added in the process, and doesn't make sense in the code as posted.

Code:

    /* obsolete and possibly introduces false errors */
    if (path == NULL) {
        fprintf(stderr, "Out of memory error\n");
        return 0;
    }


sheds 11-03-2004 01:43 PM

Why do you have to go through all subfolders instead of deleting the entire directory at once, i understand there is an option where you delete a directory neverminding what's in it, right?

Hko 11-03-2004 02:55 PM

Yes, the "rm" program has an option to delete an entire directory tree. But this is about how the "rm" program does that.

sheds 11-04-2004 02:03 AM

Oh i see. You are trying to implement rm. Cool.

dwijesh 04-30-2009 04:55 AM

Thanks
 
Thank you very much.
I was searching this exact problem
my first half problem is solved I need the second half

Now I was copy recursivly copy a Directory which have more than one sub directory and each directoy have directory or folders .I was to copy this entir folder to a different location through C and linux platform.

my problem is:
cd

1. rm -rf * [solved by above answar]

2. cp -r /mnt/usbdrive/finalPackage ~ [waiting to be solved.....]

Kindly suggest ..
I don't want to use system()

Thanks & Regards
Dwijesh Maharana

ira_2011 08-16-2011 07:23 AM

С++ delete folder recursive
 
void delete_folder_tree(const char *dirname)
{
DIR *dir;
struct dirent *entry;
char path[PATH_MAX];

if (path == NULL) {
_TRACE("Out of memory error\n");
return;
}
dir = opendir(dirname);
if (dir == NULL) {
_ERROR("Error opendir()");
return;
}

while ((entry = readdir(dir)) != NULL) {
if (strcmp(entry->d_name, ".") && strcmp(entry->d_name, "..")) {
snprintf(path, (size_t) PATH_MAX, "%s/%s", dirname, entry->d_name);
if (entry->d_type == DT_DIR) {
delete_folder_tree(path);
} else {
unlink(path);
}
}

}
closedir(dir);

rmdir(dirname);
_TRACE("(not really) Deleting: %s\n", dirname);

return;
}

Sergei Steshenko 08-16-2011 09:01 AM

Quote:

Originally Posted by ArulPrabhuT (Post 1262964)
I want to delete a directory(which contains files and subfolders) using c++ in Linux, is there any solution to do this one?

any help would be appreciated.

Yes, there is:
  1. you open your favorite browser;
  2. you navigate to your favorite web search engine;
  3. you try search terms like

C++ delete directory
C++ remove directory
.

C++ allows usage of standard "C" library which has the needed function: 'man 2 rmdir'. There is also a thing called 'recursion' which helps in your case.

Nylex 08-20-2011 02:14 AM

ira_2011, please don't drag up old threads like this. In addition, when posting code here, you should use [code] tags to preserve indentation.

dugan 08-20-2011 11:10 AM

There is now only one standard library function you need to use for this (and yes, it's standard now):

http://www.boost.org/doc/libs/1_47_0...tml#remove_all


All times are GMT -5. The time now is 01:59 PM.