tags:

views:

319

answers:

3

Is there any way in C to remove (using remove()) multiple files using a * (wildcards)? I have a set of files that all start with Index. For example: Index1.txt Index-39.txt etc. They all start with Index but I don't know what text follows. There are also other files in the same directory so deleting all files won't work.

I know you can read the directory, iterate each file name, read the the first 5 chars, compare and if it fits then delete, but, is there an easier way (this is what I currently do by the way)?

code is appreciated.

Thanks!

EDIT: I forgot to mention that this is standard C, since the code runs on Linux and Windows

+1  A: 

If you don't mind being platform-specific, you could use the system() call:

system("del index*.txt"); // DOS
system("rm index*.txt"); // unix

Here is some documentation on the system() call, which is part of the standard C library (cstdlib).

e.James
`system` is implementation specific by definition, so I always add a rider to look up the relevant vendor documentation (if you can find it). Principle of least surprises.
dirkgently
Thanks, but system() is a security nightmare.
Uri
Certainly a valid concern. I voted for Epsilon Prime :)
e.James
+3  A: 

As you point out you could use diropen, dirread, dirclose to access the directory contents, a function of your own (or transform the wildcards into a regex and use a regex library) to match, and unlink to delete.

There isn't a standard way to do this easier. There are likely to be libraries, but they won't be more efficient than what you're doing. Typically a file finding function takes a callback where you provide the matching and action part of the code. All you'd be saving is the loop.

Epsilon Prime
Thanks for the answer. I always appreciate when people tells you when something cannot be done, instead of BS'ing you.
Uri
On Unix instead of converting the wildcards to regular expressions, you should use fnmatch (http://www.opengroup.org/onlinepubs/000095399/functions/fnmatch.html).
R Samuel Klatchko
Cool! I never knew that fnmatch() existed.
Epsilon Prime
A: 

Is this all the program does? If so, let the command line do the wildcard expansion for you:

int main(int argc, char* argv[])
{
   while (argc--)
     remove(argv[argc]);
}

on Windows, you need to link against 'setargv.obj', included in the VC standard lib directory.

AShelly