Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Remove Directory 1

Status
Not open for further replies.

nappaji

Programmer
Mar 21, 2001
76
US
How do I remove a directory which is not empty.

C functions rmdir or unlink requires the directory to be empty . Is there a function to remove a non-empty directory in C????

Thanks
 
If you're in a UNIX environment, you can always just do:

[tt]system("rm -r directory");[/tt]
 
Find and delete (unlink) all the files in the directory (under Unix use the opendir, readdir, closedir calls, under Window$ use the FindFirst and FindNext calls) then delete the dir.
 
Here is a quick hack.

You would need to call stat() for your files to be safe
and check the value using the macros S_ISDIR and S_ISREG
so you can implement further (?recursive?)subdirectory removal.
Needless to say error checking is all up to you.



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

#define errstring &quot;UNHELPFUL USER ERROR MESSAGE&quot;

int rmfile(char *name);
char *basename(char *name);

int main(int argc, char **argv) {
DIR *mydir;
char buf[100], *pptr;
struct dirent *entry;

pptr = basename(argv[1]);


if ( (mydir = opendir(argv[1])) != NULL) {

while ( (entry = readdir(mydir)) != NULL) {
printf(&quot;Looking at %s\n&quot;, entry->d_name);
sprintf(buf,&quot;%s/%s&quot;,pptr,entry->d_name);
printf(&quot;Filename is %s operation returns %d,\n&quot;, buf, mfile(buf));
}

}
closedir(mydir);

return 0;
}


int rmfile(char *name) {
int x;

printf(&quot;Now unlinking name %s\n&quot;, name);
/* x = unlink(name);

return x;*/
}

char *basename(char *name) {
int i = 0, y;
char *tmp = name, *ret;

while (*name++) {
i++;
if (*name == '/') {
y = i;
}
}

if (y && (ret = malloc(sizeof name)) ) {
strncpy(ret,tmp,y);
return ret;
}

return errstring;
}
 
yes marsd: i did not really read your code
your way is sure better then the lazy: system(&quot;rm -rf xxx&quot;);
please do not re-invent 'basename()'
say extern char *basename(char *);
in your protos dont include the <name>
not: int rmfile(char *name);
but: int rmfile(char *);
:)

-----------
when they don't ask you anymore, where they are come from, and they don't tell you anymore, where they go ... you'r getting older !
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top