Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete all files in a folder, but not delete the folder using NIX standard libraries?

Tags:

I am trying to create a program that deletes the contents of the /tmp folder, I am using C/C++ on linux.

system("exec rm -r /tmp") 

deletes everything in the folder but it deletes the folder too which I dont want.

Is there any way to do this by some sort of bash script, called via system(); or is there a direct way i can do this in C/C++?

My question is similar to this one, but im not on OS X... how to delete all files in a folder, but not the folder itself?

like image 971
Finding Nemo 2 is happening. Avatar asked Jun 13 '12 02:06

Finding Nemo 2 is happening.


People also ask

How can I delete all files in a directory in C++?

std::filesystem::remove_all( path ) will recursively delete a folder at path and it will delete the file if path refers to a file not a directory.


2 Answers

#include <stdio.h> #include <dirent.h>  int main() {     // These are data types defined in the "dirent" header     DIR *theFolder = opendir("path/of/folder");     struct dirent *next_file;     char filepath[256];      while ( (next_file = readdir(theFolder)) != NULL )     {         // build the path for each file in the folder         sprintf(filepath, "%s/%s", "path/of/folder", next_file->d_name);         remove(filepath);     }     closedir(theFolder);     return 0; } 

You don't want to spawn a new shell via system() or something like that - that's a lot of overhead to do something very simple and it makes unnecessary assumptions (and dependencies) about what's available on the system.

like image 182
Demitri Avatar answered Oct 05 '22 02:10

Demitri


In C/C++, you could do:

system("exec rm -r /tmp/*") 

In Bash, you could do:

rm -r /tmp/* 

This will delete everything inside /tmp, but not /tmp itself.

like image 22
Jay Sullivan Avatar answered Oct 05 '22 02:10

Jay Sullivan