views:

192

answers:

3

hey

I just started learning c++ and am currently using codeblocks. i wanna write an application that can search for files in directory including it's subdirs, but i cant seem to find any good examples for this and i've read somewhere that this is only possible trough a library like boost.

  1. is this true?
  2. any examples for doing it without library?

thanks in advance

+3  A: 

It's also possible to use it using OS system calls, readdir on linux for example. boost (and other libraries) will allow you to write portable code for several (all?) OSes.

Here u can find elaborate examples http://faq.cprogramming.com/cgi-bin/smartfaq.cgi?answer=1046380353&id=1044780608

Drakosha
thanks the win32 example is just what i needed to see
mars
+1  A: 

Boost isn't the only way of scanning directories but it's probably the easiest way to do it in a platform-neutral way - i.e. without using a platform-specific API (such as Win32).

Here's a simple example using boost:

#include <boost/filesystem.hpp>
#include <iostream>
#include <iterator>
#include <set>

std::set<boost::filesystem::path> getDirContents (const std::string& dirName)
{
    std::set<boost::filesystem::path> paths;
    std::copy
        ( boost::filesystem::directory_iterator (dirName)
        , boost::filesystem::directory_iterator ()
        , std::inserter (paths, paths.end ())
        );

    return paths;
}

int main (int argc, char* argv[])
{
    std::set<boost::filesystem::path> paths = getDirContents ("C:\\");
    std::copy
        ( paths.begin ()
        , paths.end ()
        , std::ostream_iterator<boost::filesystem::path> (std::cout, "\n")
        );
    return 0;
}
jon hanson
won't there be a significant loss in speed when using a library?
mars
When searching files IO will be your biggest problem, not some library overhead.
tstenner
@mars, the boost classes are just thin wrappers for the underlying system API calls - the overhead should be negligble, esp, as tstenner says, compared to the time the actual API calls will take.
jon hanson
+2  A: 

Yes, it's true: standard C++ does not have APIs for listing the content of a directory.

So you either do it through a library (Boost or others) or through the native calls for the operating system you're using (FindFirstFile/FindNextFile on Windows, opendir/readdir on Unix). Others answers have example code.

But if you just started learning C++ it is probably better to not struggle with these for now. Focus on learning standard C++ for the beginning. Writing the application you had in mind is an useful exercise but I would postpone it a little until after you are more familiar with standard C++.

Catalin Iacob
Isn't opendir/readdir POSIX?
mrduclaw