tags:

views:

467

answers:

5

I am writing a program in C++ where I have 500 folders, each containing one text file. I want to read each text file from each folder in C++.

How can I accomplish this?

+3  A: 

findfirstfile

PoweRoy
+6  A: 

The C++ Standard does not specify any directory functions, so you will have to use something implementation-specific. For example, on Windows you can use the chdir() function. declared in <direct.h>.

BTW, please note it's a good idea to indicate which operating system(s) you are interested in when posting questions like this.

anon
A: 

I have nothing to say.

v3
Rich B on the warpath :-)
Thomas L Holaday
+1  A: 

You don't want to change dir, but just open them to read their entries ( see opendir() )

Usually I find it easier to handle the complete path than rely on the process's current directory.

fa.
+9  A: 

If you want a neat and portable way to access files and directories, look no further than Boost.Filesystem. You should browse through the documentation to find exactly what you need. Below is a suggestion of how you could use the framework to get things done.

#include <iostream>
#include <filesystem>

using std::tr2::sys;
using std::cout;

void do_something_with_file( std::string const& p )
{
  std::cout << "Found file : " << p << std::end;
}

void explore_directory( std::string const& p )
{
    for (directory_iterator itr(p); itr!=directory_iterator(); ++itr)
    {
      if( is_directory(itr->status()) )
      {
        explore_directory(itr->path().filename());
      }
      else if( is_regular_file(itr->status()) )
      {
        do_something_with_file(itr->path().filename());
      }
    }
}

int main(int argc, char* argv[])
{
  std::string p(argc <= 1 ? "." : argv[1]);

  if (is_directory(p))
  {
    explore_directory(p);
  }
  else cout << (exists(p) : "Found: " : "Not found: ") << p << '\n';

  return 0;
}
Benoît
I'm amazed that none of the previous 4 posts recommended boost.
Adrian Grigore
it gives a chance to learn to do it with the native system calls
fa.
You always can, but it's, in my opinion, not the most efficient (as in time-to-code) way to do it.
Benoît
not everyone is s boost fan
anon
I can see that but i guess i don't understand why :)
Benoît