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 bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Removing all files in a certain directory (but not any subdirectories)

Status
Not open for further replies.

marcuswork

Programmer
Oct 3, 2003
2
US
Hey all, I have a C++ program that is manipulating files in a Unix (sun) directory. Let's say I have a main_dir and then inside of main_dir are a bunch of files and a temp_dir. I want to delete all the files "except" for the temp_dir. Is there a single command I could use to remove "all" files?

I've tried doing:
remove("main_dir/*); // note these are strings converted
// into char* pointers in reality
remove("main_dir/*.*"); // by calling my_string.c_str()
system("rm *");

None of these work. Calling the &quot;system&quot; command gives an error that it can't delete a certain file (usually the first one it tries to delete). Also, I've tried to use scandir() but get an error that it can't find the include file <sys/dir.h>. Any help on this would be greatly appreciated.

Also, after removing all files from main_dir, I'd like to &quot;move&quot; all the files from the nested temp_dir back into the main_dir. How would I accomplish this in C++ on a Sun machine?

Thanks,
Marcus
 
It seems that there is some problem with the permissions and thats why you are unable to delete the files using system. Check the permissions of your login and the final directory(main_dir). That is the simplest solution.

&quot;it can't find the include file <sys/dir.h>.&quot;

It seems that there is some problem with your code or something. This file is a must and I think that your system shall have it. Solution that was coming to my mind was also by using the function calls from dir.h

You open your main directory by calling opendir(). Then read the contents of the directory by readdir(). Check, if read entity is a file then delete it. Also somebody recently posted for a function called ftw() which helps recursive traversal.

For deletion you can use unlink()/remove().
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top