Chat LIVE With Programming Experts! There Are 23 Online Right Now...

Welcome to Dream.In.Code
Become a C++ Expert!

Join 244,258 C++ Programmers for FREE! Get instant access to thousands of C++ experts, tutorials, code snippets, and more! There are 1,281 people online right now. Registration is fast and FREE... Join Now!




Accessing directories in C/C++ Part I

 
Reply to this topicStart new topic

> Accessing directories in C/C++ Part I, #include <dirent.h>

gabehabe
Group Icon



post 7 Aug, 2008 - 11:53 AM
Post #1


Accessing Directories

This will work in either C or C++ since the libraries are C standard. Since this code can apply to C too, I'm going to use printf() for output. At the end, I will post a C++ equivalent, but the only difference is actually outputting to the console (cout/printf)

Note:
In this tutorial, I'm going to cover the uses of the basic functions from dirent.h There are more, but they require more libraries. These additional functions will be explained in a part two! smile.gif i will be explaining the following functions in this tutorial:
  • opendir() to open a directory
  • readdir() to read a directory
  • closedir() to close a directory

So, let's begin!

When we work with the basics of directory access, the only header we need is #include <dirent.h>
However, since I want to show you a working example, I'm also including some other libraries, which you have most likely come across before:
  • #include <stdlib.h> for the exit () function (used after an error has occurred)
  • #include <stdio.h> for the printf () function, which I'm sure you already know!

So, the start of our program looks like this:
cpp
#include <dirent.h> // directory header
#include <stdio.h> // printf()
#include <stdlib.h> // exit()

int main () // entry point of the program
{
Nothing new there, apart from dirent, which you're going to learn about now! smile.gif

Now it's time to create a DIR * which is simply a pointer to a directory. Here:
cpp
    DIR *pdir = NULL; // remember, it's good practice to initialise a pointer to NULL!

Next, we need a struct dirent * which is basically used when reading a directory. The function readdir() will return a dirent, and dirent stores some useful information. In this example, we will be accessing d_name which is a member of dirent This may sound a little confusing now, but fear not! It will all become clear!
cpp
    struct dirent *pent = NULL;

And now it's time to open a directory! In this tutorial, I will use the program's directory, which is accessed with "." The reason that I'm using the program's directory is that it's one that is common to us all. It's no good me telling you to access "C:\\" if you're running Linux now, is it?! I'm also going to perform a check to see if it directory was opened correctly. If it wasn't, then the program will exit, since it's not worth continuing, is it?
cpp
    pdir = opendir ("."); // "." will refer to the current directory
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");
exit (1); // exit the program, using 1 as the status (most common for a failed execution)
} // end if

Now we're getting somewhere!!! w00t! However, there will be no output yet. We next need to read the directory, and output everything that's in it. I also perform another check, to make sure that it has been read correctly. Simple enough, really:
cpp
    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 ("ERROR! pent could not be initialised correctly");
exit (3);
}
// otherwise, it was initialised correctly. let's print it on the console:
printf ("%s\n", pent->d_name);
}

Finally, all we need to do is close the directory, and exit the program.
cpp
    closedir (pdir);

return 0; // everything went OK
}

And that's all there is to basic directory access! That wasn't so difficult, was it?

Now I guess you're thinking: "what do I do next?"
Well, you can practice this skill a little~ practice makes perfect!

And, you can look forward to reading part two of this tutorial~ smile.gif

Oh yeah, real quick, here is the complete code, in both C and C++ (scroll down for C++)

C CODE!
cpp
#include <dirent.h> // directory header
#include <stdio.h> // printf()
#include <stdlib.h> // exit()

int main () // entry point of the program
{
// 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!
struct dirent *pent = NULL;

// I used the current directory, since this is one which will apply to anyone reading
// this tutorial~ If I said "C:\\" and you're on Linux, it may get a little confusing!
pdir = opendir ("."); // "." will refer to the current directory
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");
exit (3);
} // 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 ("ERROR! pent could not be initialised correctly");
exit (3);
// 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);

return 0; // everything went OK
}

C++ CODE!
cpp
#include <dirent.h> // directory header
#include <iostream> // input/output stream

// use a few things from the std namespace for console I/O
using std::cout;
using std::cin;
using std::endl;

int main () // entry point of the program
{
// 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 ("."); // "." will refer to the current directory
struct dirent *pent = NULL;

// I used the current directory, since this is one which will apply to anyone reading
// this tutorial~ If I said "C:\\" and you're on Linux, it may get a little confusing!
if (pdir == NULL) // if pdir wasn't initialised correctly
{ // print an error message and exit the program
cout << "\nERROR! pdir could not be initialised correctly";
exit (3);
} // 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
cout << "\nERROR! pent could not be initialised correctly";
exit (3);
}
// otherwise, it was initialised correctly. Let's print it on the console:
cout << pent->d_name << endl;
}

// finally, let's close the directory
closedir (pdir);

cin.get (); // pause for input
return EXIT_SUCCESS; // everything went OK
}
Go to the top of the page
+Quote Post


Register to Make This Ad Go Away!

born2c0de
Group Icon



post 8 Aug, 2008 - 03:19 AM
Post #2
QUOTE
exit (3); // pause for three seconds before exiting

Which header file is exit defined in?

As far as I know, the one defined in stdlib.h takes a status parameter, and doesn't pause for 'status' seconds when called.
Go to the top of the page
+Quote Post

gabehabe
Group Icon



post 8 Aug, 2008 - 03:41 PM
Post #3
blush.gif

My bad, haven't used it in a while, and I got it confused with a function I used recently. Just fixed the code.

Thanks for pointing that out icon_up.gif

You're absolutely right, exit() will exit the program with the given status.
To clarify, for those who don't already know, think of returning a value from main. Often, 0 is a successful execution, and 1 is failed execution. Calling exit(1) is basically like closing the program and returning a status of 1.
Go to the top of the page
+Quote Post


Reply to this topicStart new topic
1 User(s) are reading this topic (1 Guests and 0 Anonymous Users)
0 Members:

 


Lo-Fi Version Time is now: 7/4/09 11:14AM

Live C++ Help!

Be Social

Dream.In.Code RSS Feed Dream.In.Code LinkedIn Group Follow Us On Twitter Fan Us On Facebook

C++ Tutorials

Reference Sheets

C++ Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month