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

#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.


by using use the wildcard * character you can delete all the files with any type of extension.

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

Tags:

Linux

Unix

C++

C