Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

Deleting Directory using c++ in Linux

Posted on 2004-10-29
15
Medium Priority
?
558 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
Comment
Question by:aravindtj
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 5
  • 4
  • 4
  • +2
15 Comments
 
LVL 12

Expert Comment

by:stefan73
ID: 12443139
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
ID: 12443296
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
ID: 12443446
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
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
LVL 12

Expert Comment

by:stefan73
ID: 12443477
Basically, it's like

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

Expert Comment

by:Axter
ID: 12449931
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
ID: 12475153
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
ID: 12475398
>>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
ID: 12475450
>> 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
ID: 12475530
0
 
LVL 30

Expert Comment

by:Axter
ID: 12475602
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
ID: 12475977
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
ID: 12476680
>>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
ID: 12480632
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
ID: 12483609
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:
ArulPrabhuT earned 150 total points
ID: 12681657
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

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
Article by: evilrix
Looking for a way to avoid searching through large data sets for data that doesn't exist? A Bloom Filter might be what you need. This data structure is a probabilistic filter that allows you to avoid unnecessary searches when you know the data defin…
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 use the return statement in functions in C++. The video will also teach the user how to pass data to a function and have the function return data back for further processing.
Suggested Courses

618 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