C Linux 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;
}


This document was last updated February 28th, 2011.
Written by: Dag Jonny Nedrelid
©2007-2012 http://thronic.com


Feel free to leave a comment.
Name:
URL:
0