tags:

views:

392

answers:

2

Is it possible to open files from a given directory in C/C++ using wildcard characters?

In the sense, If I want to open files that end with "to(node_id)" from a given current directory in my program.

Example : I need to open files whose filenames end with "to4". Desired Output : It must open all the files in the current directory with filenames that end with "to4". If files from0to4, from1to4, from2to4 & from3to4 exist in the current directory, they must be opened.

If it is not possible in C/C++, is there any other programming language which allows this?

+3  A: 

Not in standard C++; you'll need to use either OS-specific function calls or a filesystem library like Boost.Filesystem.

In either case, you can get a list of files in a given directory and iterate over the list and open only the ones that match your parameters.

James McNellis
+2  A: 

You can do it with C and C++. On Windows, you might use FindFirstFile and FindNextFile.

Your platform may already do it for you. If you're running Unix, say you run the following command:

$ ./myprog *to4

The shell first expands the wildcard and then executes myprog with the expanded arguments, equivalent to

$ ./myprog from0to4 from1to4 from2to4 from3to4

in your example directory.

You asked about other languages, so the code below is how you might do it with Perl:

#! /usr/bin/perl

foreach my $file (<*to4>) {
  open my $fh, "<", $file or die "$0: open $file: $!\n";

  while (<$fh>) {
    print "$file: $_";
  }
}

For example, first create the files and then run a program that opens them:

$ for i in 0 1 2 3; do
> echo file $i > from${i}to4
> done

$ ./opento4s
from0to4: file 0
from1to4: file 1
from2to4: file 2
from3to4: file 3
Greg Bacon