# include%26lt;stdio.h%26gt;
# include"ourhdr.h"
# include%26lt;sys/stat.h%26gt;
# include%26lt;sys/types.h%26gt;
# include %26lt;dirent.h%26gt;
# include%26lt;fcntl.h%26gt;
# include%26lt;string.h%26gt;
static void removefiles(char*);
int main(int argc,char* argv[]){
removefiles(argv[1]);
exit(0);
}
static void removefiles(char* fold){
DIR *dp;
struct dirent *dirp;
struct stat statbuf;
char c[100]="/0";
char *w,*y,*z,*x;
int countfold=0;
dp=opendir(fold);
while((dirp=readdir(dp))!=NULL)
{
if((strcmp(dirp-%26gt;d_name,".")!=0) %26amp;%26amp; (strcmp(dirp-%26gt;d_name,"..")!=0))
{
strcpy(c,"./");
x=strcat(c,fold);
w=strcat(x,"/");
y=dirp-%26gt;d_name;
z=strcat(w,y);
lstat(dirp-%26gt;d_name,%26amp;statbuf);
if(S_ISREG(statbuf.st_mode)) remove(z);
else if (S_ISLNK(statbuf.st_mode))remove(z);
else if(S_ISDIR(statbuf.st_mode)){
if(remove(z)%26gt;0); // folder is empty.
else removefiles(z);
}
}
}
rmdir(fold);
}
(recursive function) problem (remove directory in c with linux)?
Looks like it should work, as is, except one small syntax error I spotted:
if(remove(z)%26gt;0); // folder is empty.
else removefiles(z);
Shouldn't be a a semicolon at the end of statement:
if(remove(z)%26gt;0)
--------------------------------------...
EDIT:
No wait, I take it back. That syntax is OK because there is nothing to do after "if(remove(z)%26gt;0); " ...the 'else' in the next line confirms that.
However, are you sure that that's how you want it to roll?
end EDIT
--------------------------------------...
Anyway, the main principles seem to be in place:
- cat the new subdirectory to the search string before each recursive call...with care to add the '/'
- use remove() for files, rmdir() for folders
- attempt remove folder only after files are deleted
- etc...
You mite need to change mode on some files to get a successful remove(), like if they're read only, system, etc, before calling remove().
Reply:Well here's the simplest way:
#include %26lt;stdlib.h%26gt;
#include %26lt;string.h%26gt;
int main( int argc, char* argv[] )
{
char cmd[256];
strcpy( cmd, "rm -f -r " );
strcat( cmd, argv[1] );
return system( cmd );
}
Reply:Without more information on what your problem is, I'll just say what I can find wrong.
#1 : No checking on number of arguments.
ie. use of argv[1], without checking argc, so if you run program without argument, it will core.
#2 : strcpy(c,"./") means you assumed that the argument MUST be relative to current directory.
This is not true if someone wants to run "removefiles /tmp/mytmp".
#3 : char c[100] is usually not enough, since in recursive folders, it is easy to exceed 100 characters in length.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment