Page 1 of 1

Accessing directories in C/C++ Part I #include <dirent.h> Rate Topic: ***** 1 Votes

#1 gabehabe  Icon User is offline

  • GabehabeSwamp
  • member icon




Reputation: 1382
  • View blog
  • Posts: 10,962
  • Joined: 06-February 08

Posted 07 August 2008 - 12:53 PM

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! :) 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:
#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! :)

Now it's time to create a DIR * which is simply a pointer to a directory. Here:
    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!
    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?
    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:
    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.
    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~ :)

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

C CODE!
#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!
#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
}


Is This A Good Question/Topic? 4
  • +

Replies To: Accessing directories in C/C++ Part I

#2 born2c0de  Icon User is offline

  • printf("I'm a %XR",195936478);
  • member icon

Reputation: 180
  • View blog
  • Posts: 4,667
  • Joined: 26-November 04

Posted 08 August 2008 - 04:19 AM

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.
Was This Post Helpful? 0
  • +
  • -

#3 gabehabe  Icon User is offline

  • GabehabeSwamp
  • member icon




Reputation: 1382
  • View blog
  • Posts: 10,962
  • Joined: 06-February 08

Posted 08 August 2008 - 04:41 PM

:blush:

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 :^:

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.
Was This Post Helpful? 0
  • +
  • -

#4 unknown v2  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 8
  • Joined: 06-December 08

Posted 12 September 2009 - 06:32 PM

Just wondering if you could point me in the right direction for the dirent.h you are using, I used to have it but I lost it :(
Was This Post Helpful? 0
  • +
  • -

#5 Jimbo7136  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 33
  • Joined: 01-July 12

Posted 05 July 2012 - 04:59 PM

Thank you very much for taking the time to write this tutorial.

I found it very educational.

I did run into one snag though, I'm using visual studio and got an error when trying to #include <dirent.h>.

It seems visual studio doesn't include any dirent.h, I did find this page that has dirent.h for visual studio available for download and that solved my problem.
Was This Post Helpful? 0
  • +
  • -

#6 stackoverflow  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 164
  • View blog
  • Posts: 545
  • Joined: 06-July 11

Posted 06 July 2012 - 06:51 PM

Nice tutorial-- maybe part two can include Boost IO?
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1