Download this source file


// Demo of POSIX C/C++ directory routines.  These will work in Borland C++
// too (although not up to the standard), and perhaps MS Visual C++ too.
//
// (C) 2000 by Wayne Pollock, Tampa Florida USA.  All Rights Reserved.

#include <iostream>
#include <direct>  // in POSIX, <unistd>
#include <dirent>

using namespace std;

int main ()
{
	char buf[256] = ".";  // dot means the current directory.
   char* newDirName = "NewDir";

   if ( chdir( "\\temp" ) == -1 )   // note the double backslash!
      cerr << "Can't change the current directory!\n";

   if ( getcwd( buf, sizeof(buf) )  == NULL )
      cout << "Can't get current working directory!\n";
   cout << "The current working directory is " << buf << ".\n";

   if ( mkdir( newDirName ) != 0 )  // POSIX requires a second arg "mode"!
   	cerr << "Can't create a new directory!\n";

   DIR *dir;
   dirent *ent;
 
   if ( ( dir = opendir(buf) ) == NULL )
   	cerr << "Unable to open directory!\n";
   cout << "\n Files in " << buf << ":\n";

   while ( (ent = readdir(dir) ) != NULL )
      cout << "\t" << ent->d_name << endl;

   // use: rewinddir(dir) to scan the directory again.
   // Note: you can use stat(file) to return info about a file.

   if ( closedir(dir) != 0 )
      cerr << "Unable to close directory!\n";

   if ( rmdir( newDirName ) != 0 )
      cerr << "Can't delete directory " << newDirName << "!\n";

   return 0;
}