开发者

Read All Files in Directory?

How would I go about reading all files in a dir开发者_如何学运维ectory?

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++?


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


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


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.


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


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;
}


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜