tags:

views:

134

answers:

6

How would I go about reading all files in a directory?

In C# I would get a DirectoryInfo object, and get all files into a FileInfo[] object.

Is there similar functionality in the STD namespace in C++?

+1  A: 

No, how that is done depends on what operating system you're on.

Since you're using C#, I assume you're using the Windows operating system. For windows, see http://msdn.microsoft.com/en-us/library/aa365200(VS.85).aspx on how to list all the files in a directory. Then use that information to open those files.

In silico
A: 

I don't think there is anything in std, but you can use the readdir() and opendir() C functions.

stribika
+7  A: 

For a free, portable solution try the Boost Filesystem Library.

Fred Larson
+1 the thing to make clear is that C++ doesn't know anything about directories.
frankc
@userxxxx - it will soon.
Noah Roberts
This is the right solution. The Boost Filesystem Library has been accepted into the upcoming TR2, so it should eventually make it into the C++ standard itself.
Nate
+4  A: 

Using Windows API, you can find all the files in a directory using FindFirstFile() with FindNextFile() in a loop.

Dave18
Probably what the user needed but not what he asked.
Panic
A: 

To elaborate on Dave18's answer, I've got a function right here that uses FindFirst/NextFile. If you're coming from C#, it probably isn't terribly straightforward, so an example could help.

bool EnumDirectory( LPCTSTR szPath, std::vector<std::string>& rtList,
                    bool bIncludeDirs, bool bIncludeFiles )
{
   HANDLE hFind;
   WIN32_FIND_DATA FindFileData;
   std::string strDirPath = ( szPath ) ? szPath : "";
   // Throw on a trailing backslash if not included
   if( !strDirPath.empty() && strDirPath[ strDirPath.length() - 1 ] != '\\' )
      strDirPath += "\\";
   // Looking for all files, so *
   strDirPath += "*";

   hFind = FindFirstFile( strDirPath.c_str(), &FindFileData );
   if( hFind == INVALID_HANDLE_VALUE ) return false;
   while( FindNextFile( hFind, &FindFileData ) )
   {
      if( !strcmp( FindFileData.cFileName, "." ) ||
          !strcmp( FindFileData.cFileName, ".." ) ) continue;

      if( FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY )
      {
         if( bIncludeDirs ) rtList.push_back( FindFileData.cFileName );
      }
      else
      {
         if( bIncludeFiles ) rtList.push_back( FindFileData.cFileName );
      }
   }
   FindClose( hFind );
   return true;
}
Doug Kavendek
A: 

Use the boost filesystem library (as someone else mentioned). The same API will be in the next standard library so it is certainly the best approach to use with new projects unless you absolutely need something it doesn't do.

Noah Roberts