What's Here?
- Members: 117,610
- Replies: 431,993
- Topics: 66,701
- Snippets: 2,395
- Tutorials: 631
- Total Online: 2,442
- Members: 54
- Guests: 2,388
Who's Online?
|
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
|
|
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
/*
* A function to list all contents of a given directory
* author: Danny Battison
* contact: gabehabe@hotmail.com
*/
#include <dirent.h> // directory header
#include <cstdio>
void listdir (const char *path)
{
// first off, we need to create a pointer to a directory
DIR *pdir = NULL; // remember, it's good practice to initialise a pointer to NULL!
pdir = opendir (path); // "." will refer to the current directory
struct dirent *pent = NULL;
if (pdir == NULL) // if pdir wasn't initialised correctly
{ // print an error message and exit the program
printf ("\nERROR! pdir could not be initialised correctly");
return; // exit the function
} // end if
while (pent = readdir (pdir)) // while there is still something in the directory to list
{
if (pent == NULL) // if pent has not been initialised correctly
{ // print an error message, and exit the program
printf ("\nERROR! pent could not be initialised correctly");
return; // exit the function
}
// otherwise, it was initialised correctly. let's print it on the console:
printf ("%s\n", pent->d_name);
}
// finally, let's close the directory
closedir (pdir);
}
/** EXAMPLE USAGE **/
int main ()
{
listdir ("C:\\");
return 0;
}
Copy & Paste
|
|
|
Reference Sheets
Bye Bye Ads
Free DIC T-Shirt
Related Sites
Monthly Drawing
Partners
Top Contributors
Top 10 Kudos This Month
|