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
  • 59,987
  • 13
  • 123
  • 180
Nefzen
  • 7,819
  • 14
  • 36
  • 34

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,313
  • 39
  • 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
  • 733,204
  • 149
  • 1,241
  • 1,454
  • 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.
  • 34,624
  • 22
  • 86
  • 128
0

Poco::DirectoryIterator is an alternative

Agnel Kurian
  • 57,975
  • 43
  • 146
  • 217
-3

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

the_drow
  • 18,571
  • 25
  • 126
  • 193