C program to delete files which match a pattern

This is a C program for deleting a lot of files in a directory which match a pattern. In this case the pattern is for the file to match kanji_cgi_log_*.

The method used is to first of all go through all the files in the current directory and find any files which match the pattern, and put them into a linked list. Then the linked list is traversed from the start, and each file is deleted using unlink.

The program accepts one option, -v, which makes it print messages about what it is doing as it works. Any other option is ignored.

If a deletion fails, the program reports an error but continues working through the list.

#include <stdlib.h>
#include <stdio.h>
#include <dirent.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>

static const char * deletepattern = "kanji_cgi_log_";

typedef struct df {
    char * name;
    struct df * next;
}
df_t;

int main (int argc, char ** argv)
{
    DIR * d;
    int l;
    int verbose = 0;
    df_t * first;
    df_t * last;
    df_t * next;
    df_t * prev;

    if (argc > 1) {
	int i;
	for (i = 1; i < argc; i++) {
	    if (strcmp (argv[i], "-v") == 0) {
		verbose = 1;
		break;
	    }
	    fprintf (stderr, "Unknown option '%s': ignoring.\n", argv[i]);
	}
    }

    d = opendir (".");
    if (! d) {
	fprintf (stderr, "Cannot open current directory.\n");
	exit (EXIT_FAILURE);
    }
    l = strlen (deletepattern);
    first = 0;
    while (1) {
	struct dirent * entry;
	const char * name;
	entry = readdir (d);
	if (! entry) {
	    break;
	}
	name = entry->d_name;
	if (verbose) {
	    printf ("Found '%s': ", name);
	}
	if (strncmp (name, deletepattern, l) == 0) {
	    df_t * df;
	    df = calloc (1, sizeof (df_t));
	    if (! df) {
		fprintf (stderr, "%s:%d: out of memory.\n",
			 __FILE__, __LINE__);
		exit (EXIT_FAILURE);
	    }
	    df->name = strdup (name);
	    if (! df->name) {
		fprintf (stderr, "%s:%d: out of memory.\n",
			 __FILE__, __LINE__);
		exit (EXIT_FAILURE);
	    }
	    if (! first) {
		first = df;
		last = df;
	    }
	    else {
		last->next = df;
	    }
	    last = df;
	}
	else {
	    if (verbose) {
		printf ("not ");
	    }
	}
	if (verbose) {
	    printf ("deleting.\n");
	}
    }
    closedir (d);
    next = first;
    prev = 0;
    while (next) {
	char * name;
	int status;
	name = next->name;
	if (verbose) {
	    printf ("Deleting '%s'.\n", name);
	}
	status = unlink (name);

	if (status != 0) {
	    fprintf (stderr, "Could not delete '%s': %s: continuing.\n",
		     name, strerror (errno));
	}
	free (name);
	prev = next;
	next = next->next;
	free (prev);
    }

    return 0;
}

(download)


Copyright © Ben Bullock 2009-2023. All rights reserved. For comments, questions, and corrections, please email Ben Bullock (benkasminbullock@gmail.com) or use the discussion group at Google Groups. / Privacy / Disclaimer