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

56,694

Solution 1

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.

Solution 2

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

Solution 3

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

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

Solution 4

you can do

system("exec find /tmp -mindepth 1 -exec rm {} ';'");

Solution 5

In C/C++ you can use (including hidden directories):

system("rm -r /tmp/* /tmp/.*");
system("find /tmp -mindepth 1 -delete");

But what if 'rm' or 'find' utilities are not availabe to sh?, better go 'ftw' and 'remove':

#define _XOPEN_SOURCE 500
#include <ftw.h>

static int remove_cb(const char *fpath, const struct stat *sb, int typeFlag, struct FTW *ftwbuf)
{
    if (ftwbuf->level)
        remove(fpath);
    return 0;
}

int main(void)
{
    nftw("./dir", remove_cb,  10, FTW_DEPTH);
    return 0;
}
Share:
56,694
Finding Nemo 2 is happening.
Author by

Finding Nemo 2 is happening.

Updated on November 09, 2020

Comments

  • Finding Nemo 2 is happening.
    Finding Nemo 2 is happening. over 3 years

    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?