file deletion in a directory with some conditions .

file deletion in a directory with some conditions .

Post by aki » Fri, 01 Aug 2008 19:35:10

Hi All,

I describe the problem as below.

A directory( path known) , contains 0 to any number of files .
The file names are with following structure :

For example :



i have to perform delete operation on the file with matching three
fields .
OMCID , NETYPE, NENAME (All three known )

Could somebody try to answer the problem . or tel how to proceed


file deletion in a directory with some conditions .

Post by John Gordo » Fri, 01 Aug 2008 23:23:13

In < XXXX@XXXXX.COM > aki < XXXX@XXXXX.COM > writes:


John Gordon A is for Amy, who fell down the stairs
XXXX@XXXXX.COM B is for Basil, *** ed by bears
-- Edward Gorey, "The Gashlycrumb Tinies"


file deletion in a directory with some conditions .

Post by aki » Sat, 02 Aug 2008 14:50:07

thanks for answering .
Now seeing your answer for my problem i feel i was short on providing
all required information .
My apologies for that .
Some critics suggested this is right group to pose this problem ,
anyways i am a newbie.
Well i want to write a C++ code for solving above problem.
One way of doing which seems very normal is
*iterating in a directory for all files
* matching the file to be deletes
* perform delete operation on the file
Second thing i have in mind is to do this job using a script .
i can pass three matching mentioned field and directory to the script
(perferbaly a perl one ), rest ,
script has to be written to perform the job
But from coding point of view , i donot not much .
can somebody help .

file deletion in a directory with some conditions .

Post by jt » Sat, 02 Aug 2008 21:04:03

Use opendir(2), followed by repeated calls of readdir(2) to get
information about all the files, including their names.

Now this depends on what you mean by "matching". Could be as
easy as a simple strncmp() (or a C++ equivalent), but also
could require using a regex library.

Simply call unlink(2) if the file name matched.

With Perl this probably can be written in less than 3 minutes,
using the opendir() function followed by a loop over readdir(),
deleting the files that match with unlink(). Since I still don't
know what you exactly mean by "matching" I can just speculate that
something like this will do the job

use strict;
use warnings;

die "Not enough command line arguments\n" unless @ARGV >= 4;

my $dir = shift @ARGV;
my $regex = "$ARGV[ 0 ]_$ARGV[ 1 ]_$ARGV[ 2 ]_.*" .

opendir my $d, $dir or die "Can't open directory: $!.\n";

for ( readdir $d ) {
next unless /^$regex$/o;
unlink "$dir/$_" or print "Can't delete file $dir/$_: $!\n";
closedir $d;

Of course you must make sure that only the right files match.
And note that Perl's unlink() behaves like 'rm -f', i.e. it
will also delete files for which no write permission is set,
so be careful.
Regards, Jens
\ Jens Thoms Toerring ___ XXXX@XXXXX.COM