Blog / Home
About
Media Gallery

Welcome
to
Thronic.com

ժʝ_

Autodelete Old Files


A small C program I wrote for Linux to delete files that has not been accessed for 30 days.

#include <sys/stat.h>
#include <stdio.h>
#include <dirent.h>

int main()
{
       DIR *dir;
       struct dirent *d;
       struct stat buf;
       int days;
       int curtime;

       curtime = time(0);
       dir = opendir("./");

       while (d = readdir(dir)) {
               if (strcmp(d->d_name, ".") == 0 ||
                   strcmp(d->d_name, "..") == 0)
                   continue;

               stat(d->d_name, &buf);
               days = (curtime - buf.st_atime) / 86400;

               if (days > 30)
                       remove(d->d_name);
       }
       closedir(dir);

       printf("Deleted all files not accessed for 30 days.\n");
       return 0;
}

BASH equivalent
$ find ./* -atime +30 -type f -delete



Original Post: Jan 27th, '22 18:38 CET.
Updated: Jan 27th, '22 18:40 CET.

C/C++ GNU/Linux
π