How to delete multiple C files using wildcards?

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

I know that you can read the directory, iterate each file name, read the first 5 characters, compare, and then delete, but is there an easier way (this is what I’m doing right now)?

This is standard C since the code works on Linux and Windows.

+6
c wildcard file-io
source share
3 answers

As you point out, you can use diropen, dirread, dirclose to access the contents of the directory, a function of your own (or convert wildcards to a regular expression, and use the regular expression library) to match and unlink for deletion.

There is no standard way to make this easier. Most likely there will be libraries, but they will not be more effective than what you do. Typically, the file search function will call back where you provide the relevant and valid part of the code. All you want to save is a loop.

+9
source share

If you don't mind being platform oriented, you can use the system() call:

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

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

+6
source share

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

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

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

0
source share

All Articles