LinuxQuestions.org
Support LQ: Use code LQ3 and save $3 on Domain Registration
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.

Notices



Reply
 
Search this Thread
Old 10-29-2004, 07:12 AM   #1
ArulPrabhuT
LQ Newbie
 
Registered: Aug 2004
Posts: 16

Rep: Reputation: 0
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.
 
Old 10-29-2004, 08:36 AM   #2
Hko
Senior Member
 
Registered: Aug 2002
Location: Groningen, The Netherlands
Distribution: ubuntu
Posts: 2,530

Rep: Reputation: 108Reputation: 108
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;
}
 
Old 11-01-2004, 09:00 AM   #3
ArulPrabhuT
LQ Newbie
 
Registered: Aug 2004
Posts: 16

Original Poster
Rep: Reputation: 0
Thanks Hko
thanks for the solution with this example i managed to delete the non-empty directory.
 
Old 11-01-2004, 11:44 AM   #4
Hko
Senior Member
 
Registered: Aug 2002
Location: Groningen, The Netherlands
Distribution: ubuntu
Posts: 2,530

Rep: Reputation: 108Reputation: 108
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;
    }
 
Old 11-03-2004, 02:43 PM   #5
sheds
Member
 
Registered: Oct 2004
Location: Costa Rica
Distribution: Mandrake 9.1
Posts: 30

Rep: Reputation: 15
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?
 
Old 11-03-2004, 03:55 PM   #6
Hko
Senior Member
 
Registered: Aug 2002
Location: Groningen, The Netherlands
Distribution: ubuntu
Posts: 2,530

Rep: Reputation: 108Reputation: 108
Yes, the "rm" program has an option to delete an entire directory tree. But this is about how the "rm" program does that.
 
Old 11-04-2004, 03:03 AM   #7
sheds
Member
 
Registered: Oct 2004
Location: Costa Rica
Distribution: Mandrake 9.1
Posts: 30

Rep: Reputation: 15
Oh i see. You are trying to implement rm. Cool.
 
Old 04-30-2009, 05:55 AM   #8
dwijesh
LQ Newbie
 
Registered: Apr 2009
Posts: 8

Rep: Reputation: 0
Smile 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
 
Old 08-16-2011, 08:23 AM   #9
ira_2011
LQ Newbie
 
Registered: Aug 2011
Posts: 1

Rep: Reputation: Disabled
С++ 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;
}
 
Old 08-16-2011, 10:01 AM   #10
Sergei Steshenko
Senior Member
 
Registered: May 2005
Posts: 4,481

Rep: Reputation: 453Reputation: 453Reputation: 453Reputation: 453Reputation: 453
Quote:
Originally Posted by ArulPrabhuT View Post
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.
 
Old 08-20-2011, 03:14 AM   #11
Nylex
LQ Addict
 
Registered: Jul 2003
Location: London, UK
Distribution: Slackware
Posts: 7,464

Rep: Reputation: Disabled
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.
 
Old 08-20-2011, 12:10 PM   #12
dugan
Guru
 
Registered: Nov 2003
Location: Canada
Distribution: distro hopper
Posts: 5,000

Rep: Reputation: 1558Reputation: 1558Reputation: 1558Reputation: 1558Reputation: 1558Reputation: 1558Reputation: 1558Reputation: 1558Reputation: 1558Reputation: 1558Reputation: 1558
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

Last edited by dugan; 08-20-2011 at 12:12 PM.
 
  


Reply


Thread Tools Search this Thread
Search this Thread:

Advanced Search

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
deleting directory w/o descending STAGED Linux - Newbie 5 08-24-2005 09:39 AM
"WARNING: Circular directory structure" error when deleting directory pistonbrew Linux - Software 5 02-03-2005 07:05 AM
deleting old /usr directory after a move... jimieee Linux - General 2 12-26-2003 06:15 PM
Deleting a directory... closet geek Linux - General 7 07-09-2003 07:25 AM
deleting non-empty directory sadiboyz Linux - Newbie 2 04-21-2003 10:29 PM


All times are GMT -5. The time now is 11:41 AM.

Main Menu
Advertisement
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
identi.ca: @linuxquestions
Facebook: linuxquestions Google+: linuxquestions
Open Source Consulting | Domain Registration