Wednesday, April 20, 2011

How can I change to another directory in C++?

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?

From stackoverflow
  • findfirstfile

  • 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.

  • I have nothing to say.

    Thomas L Holaday : Rich B on the warpath :-)
  • 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.

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

0 comments:

Post a Comment