Page 1 of 1

Accessing Directories in C/C++ Part II #include <dirent.h> Rate Topic: -----

#1 gabehabe  Icon User is offline

  • GabehabeSwamp
  • member icon




Reputation: 1376
  • View blog
  • Posts: 10,951
  • Joined: 06-February 08

Posted 08 August 2008 - 11:14 AM

Working with directories Part II
Creating and removing directories!

First off, if you haven't already, I suggest you read Part I of this tutorial, since a function which I have written will utilise everything that is taught in that tutorial.

Next, take a look at this snippet which I wrote. It should make sense, if you understood Part I.

Good, now we're ready to start. I will be making use of that snippet in this tutorial, to show our progress.

Let's begin!

What are we going to cover in this tutorial?
Well, in Part I, we learned how to access a directory, using DIR* and dirent*
Now, in this tutorial, we will learn how to use some (simple) functions, which perform the following tasks:
  • Creating a new directory
  • Deleting a directory
  • Changing our active directory
  • Getting the whole path of the current directory

As with Part I, this is compatible with both C++ and C, therefore I will provide the main code in C, and convert it to C++ at the end. (Again, the only difference is console output)

First off, I'm going to give you the bulk of the code. This is the includes and the function which we will use to list the contents of the current directory:
#include <dirent.h>
#include <stdio.h>
#include <stdlib.h>

void listdir (const char *path);

int main ()
{
    // example code will go here
    return 0;
}

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);
}

Creating a new directory
We can do this with a call to a simple function, call mkdir() like so:
mkdir (".\\dream.in.code");

The . represents our current directory (by default, this is the directory from which the program was launched)

So, now we have created a new folder called "dream.in.code"

Getting the current directory
This can be done with a call to a function called getcwd() like so:
printf ("Currently viewing:\n%s\n", getcwd(NULL,0));
As you can see, we are outputting the return value of the function, which is a string referring to the path of the current directory. Note that the function accepts two parameters. We aren't going to go into detail right now, since this is just the basics of directory access, but just remember that you can pass NULL,0 to it to get the current path :)

Just to clarify that our dream.in.code folder has been created successfully, let's list the contents of our current directory, using my snippet:
listdir (".");
Remember, . refers to the current path. Now, if you run the program, you should see a folder called dream.in.code at the bottom of the list. Now let's move into that folder!

Changing the active directory
Again, all that we need to do is make a call to a simple function called chdir() I'm going to do this, and call the getcwd() and listdir() functions for the output, to keep output clear.
    chdir (".\\dream.in.code");
    printf ("\nCurrently viewing:\n%s\n", getcwd(NULL,0));
    listdir (".");
NOTE: At this point, the output from this listdir() call should just be:
.
..

because . refers to the current directory, and .. refers to the parent directory. There will be nothing else, since we have not put anything into this folder.

Now, just for clarity, I'm going to move back a folder, using .. and output the current path, like so:
    chdir ("..\\"); // move back one
    printf ("Currently viewing:\n%s\n", getcwd(NULL,0));
Finally, let's remove our "dream.in.code" directory.

Removing a directory
Yet another single function call! Isn't this directory stuff easy? Now, to remove a directory, we can make a call to rmdir() like so:
    rmdir (".\dream.in.code");
And finally, I'll make another call to my snippet in order to reveal on the console that our directory has gone:
    listdir (".");


And that's all there is to it!

Why not go down to the local bar and try to pick up some girls with your super cool new directory accessing skills? I'm sure they'll be impressed! :)

Now for the final code again!

C CODE!
#include <dirent.h>
#include <stdio.h>
#include <stdlib.h>

void listdir (const char *path);

int main ()
{
    if (!mkdir (".\\dream.in.code"))
    {
        printf ("mkdir() unsuccessful. Terminating...");
        exit (3); // exit after a 3 second pause
    } // otherwise, it was created, so we can continue
    printf ("dream.in.code folder created successfully!");
    printf ("Currently viewing:\n%s\n", getcwd(NULL,0));
    listdir (".");
    printf ("\nMoving into our newly created directory");
    chdir (".\\dream.in.code");
    printf ("\nCurrently viewing:\n%s\n", getcwd(NULL,0));
    listdir (".");
    chdir ("..\\"); // move back one
    rmdir (".\dream.in.code");
    listdir (".");

    return 0;

}

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);
}

C++ CODE!
#include <dirent.h>
#include <cstdio> // for the snippet
#include <iostream> // for output

void listdir (const char *path);

int main ()
{
    if (!mkdir (".\\dream.in.code"))
    {
        printf ("mkdir() unsuccessful. Terminating...");
        exit (3); // exit after a 3 second pause
    } // otherwise, it was created, so we can continue
    std::cout << "dream.in.code folder created successfully!"
              << "Currently viewing:\n%s\n" << getcwd(NULL,0);
    listdir (".");
    std::cout << "\nMoving into our newly created directory";
    chdir (".\\dream.in.code");
    std::cout << "\nCurrently viewing:\n%s\n" << getcwd(NULL,0);
    listdir (".");
    chdir ("..\\"); // move back one
    rmdir (".\dream.in.code");
    listdir (".");

    std::cin.get (); // pause for input
    return EXIT_SUCCESS; // program was executed successfully

}

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);
}


Is This A Good Question/Topic? 0
  • +

Replies To: Accessing Directories in C/C++ Part II

#2 Techno Mage  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 86
  • Joined: 10-June 07

Posted 27 August 2008 - 07:15 PM

I believe that you need to have an access code or something with mkdir(). Like,

mkdir(path,code[like ios::whatever])


However, I must say that I'm having a real problem with mkdir(). I think I'm getting a segfault from it.

First off, I can't find it in any reference guide (well, no real info on the net, not even on cplusplus.com).

Second, what are the possible codes for for mkdir? Can't find them anywhere! I have no access to this directory I create either. Like, I click on it and I'm told I don't have the permissions to access it. This is Linux by the way.

Do I have to "open" a folder in order to write to it? I'm trying to make this directory and just write files to it but now I think that one problem is that I haven't opened the directory.

PS: This is unrelated but how can I enter a number into a string and have it increment? I was having a problem with that.

This post has been edited by Techno Mage: 28 August 2008 - 07:03 PM

Was This Post Helpful? 0
  • +
  • -

#3 gabehabe  Icon User is offline

  • GabehabeSwamp
  • member icon




Reputation: 1376
  • View blog
  • Posts: 10,951
  • Joined: 06-February 08

Posted 01 September 2008 - 12:37 PM

It must be different for Linux, everything that I wrote about up there is tried and tested on Windows, and worked without flaws.

Sorry, I'm not a Linux expert :(
Was This Post Helpful? 0
  • +
  • -

#4 khaotic  Icon User is offline

  • New D.I.C Head

Reputation: -4
  • View blog
  • Posts: 6
  • Joined: 27-June 09

Posted 11 December 2010 - 11:35 PM

Great job bud
Was This Post Helpful? 0
  • +
  • -

#5 novacrazy  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 14
  • View blog
  • Posts: 117
  • Joined: 01-March 11

Posted 17 August 2011 - 01:41 AM

I'd also recommend All of this stuff Here for working with either directories and/or files. I mean, this should work on linux, its from the GNU site, so yeah. I know all the parts I've used work on windows with MinGW.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1