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?
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.
#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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With