读取目录中的所有文件?

6

如何读取目录中的所有文件?

在C#中,我会获取一个DirectoryInfo对象,并将所有文件存储在FileInfo[]对象中。

C++的STD命名空间中是否有类似的功能?

6个回答

13

2
需要明确的是,C++ 对目录一无所知。 - frankc
这是正确的解决方案。Boost文件系统库已被接受并纳入即将发布的TR2标准,因此它最终应该会成为C++标准本身的一部分。 - Nate

6

1
可能是用户需要的,但不是他所要求的。 - Panic

1
不,如何完成这个取决于您所使用的操作系统。 由于您正在使用C#,我假设您正在使用Windows操作系统。对于Windows,请参阅http://msdn.microsoft.com/en-us/library/aa365200(VS.85).aspx以了解如何列出目录中的所有文件。然后,使用该信息打开这些文件。

1

我认为标准库中没有相关内容,但是你可以使用 readdir()opendir() C 函数。


0
为了补充Dave18的回答,我这里有一个使用FindFirst/NextFile函数的函数。如果你是从C#过来的,可能不是非常直观,所以一个例子可能会有所帮助。
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;
}

0

使用boost文件系统库(正如其他人所提到的)。相同的API将在下一个标准库中,因此对于新项目来说,这肯定是最好的方法,除非您绝对需要它无法完成的某些任务。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接