2

suppose I want to write ls or dir. how do I get the list of files in a given directory? something equivalent of .NET's Directory.GetFiles, and additional information.

not sure about the string syntax, but:

string[] filePaths = Directory.GetFiles(@"c:\MyDir\");
Drew Dormann
  • 54,920
  • 13
  • 119
  • 171
Nefzen
  • 7,659
  • 14
  • 35
  • 33

5 Answers5

23

Check out boost::filesystem, an portable and excellent library.

Edit: An example from the library:

int main(int argc, char* argv[])
{
  std::string p(argc <= 1 ? "." : argv[1]);

  if (is_directory(p))
  {
     for (directory_iterator itr(p); itr!=directory_iterator(); ++itr)
     {
       cout << itr->path().filename() << ' '; // display filename only
       if (is_regular_file(itr->status())) cout << " [" << file_size(itr->path()) << ']';
       cout << '\n';
      }
  }
  else cout << (exists(p) : "Found: " : "Not found: ") << p << '\n';

  return 0;
}
Todd Gardner
  • 13,103
  • 37
  • 51
  • I wish I knew BOOST better, I installed it on Windows but I got stuck when I tried to use it from VS. Much cleaner than that ugly winAPI. – Nefzen Jun 01 '09 at 15:37
4

Look at the FindFirstFile and FindNextFile APIs

http://msdn.microsoft.com/en-us/library/aa364418.aspx

JaredPar
  • 703,665
  • 143
  • 1,211
  • 1,438
  • I looked for quite some time for this functions in MSDN, however I found stuff like solution in .NET, J++, JavaScript and practically everything else but it. thank :) – Nefzen Jun 01 '09 at 15:40
1

In Windows: FindFirstFile, FindNextFile, and FindClose can be used to list files in a specified directory.

Pseudo code:

 Find the first file in the directory.
 do
   { 
   //

   }while(NextFile);

Close
aJ.
  • 33,420
  • 21
  • 82
  • 127
0

Poco::DirectoryIterator is an alternative

Agnel Kurian
  • 56,037
  • 41
  • 141
  • 214
-3

This is totally platform depeanded.
If on windows you should use WINAPI as suggested.

the_drow
  • 17,855
  • 25
  • 122
  • 190