Code Snippets

  

C++ Source Code


Welcome to Dream.In.Code
Getting C++ Help is Easy!

Join 117,610 C++ Programmers for FREE! Ask your question and get quick answers from experts. There are 2,442 online right now! We've got more than 500 tutorials and 2,000 snippets. Join and find out why Dream.In.Code is the #1 programming help community on the internet! Registration is fast and FREE... Join Now!


Submitted By: gabehabe
Actions:
Rating:
Views: 421

Language: C++

Last Modified: August 7, 2008
Instructions: This is also compatible with C, just replace #include with #include and away you go! =)

Snippet


  1. /*
  2. * A function to list all contents of a given directory
  3. * author: Danny Battison
  4. * contact: gabehabe@hotmail.com
  5. */
  6.  
  7. #include <dirent.h> // directory header
  8. #include <cstdio>
  9.  
  10. void listdir (const char *path)
  11. {
  12.     // first off, we need to create a pointer to a directory
  13.     DIR *pdir = NULL; // remember, it's good practice to initialise a pointer to NULL!
  14.     pdir = opendir (path); // "." will refer to the current directory
  15.     struct dirent *pent = NULL;
  16.     if (pdir == NULL) // if pdir wasn't initialised correctly
  17.     { // print an error message and exit the program
  18.         printf ("\nERROR! pdir could not be initialised correctly");
  19.         return; // exit the function
  20.     } // end if
  21.  
  22.     while (pent = readdir (pdir)) // while there is still something in the directory to list
  23.     {
  24.         if (pent == NULL) // if pent has not been initialised correctly
  25.         { // print an error message, and exit the program
  26.             printf ("\nERROR! pent could not be initialised correctly");
  27.             return; // exit the function
  28.         }
  29.         // otherwise, it was initialised correctly. let's print it on the console:
  30.         printf ("%s\n", pent->d_name);
  31.     }
  32.  
  33.     // finally, let's close the directory
  34.     closedir (pdir);
  35. }
  36.  
  37. /** EXAMPLE USAGE **/
  38. int main ()
  39. {
  40.     listdir ("C:\\");
  41.     return 0;
  42. }

Copy & Paste


Comments


bbq 2008-09-11 23:14:39

Intersting, was looking for a way to create a list of all my music, this might get me on the right path :)

dor1997 2008-09-18 08:43:07

Pretty cool! Good work!


Add comment


You must be registered and logged on to </dream.in.code> to leave comments.





Live C++ Help!

C++ Tutorials

Reference Sheets

C++ Snippets

Bye Bye Ads

Free DIC T-Shirt

T-Shirt Example

Related Sites

Monthly Drawing

Thumb Drive

Partners

Top Contributors

Top 10 Kudos This Month