UNIX & GNU/Linux - System calls - readdir()

The readdir() system call function is used to read into a directory.
The function returns a pointer to a dirent structure. This structure contains five fields but only two are POSIX standard, this is the d_name and the d_ino member.
That's the first we will use in our readdir() example.

Before starting, let's create some files. We need a folder named hello.
In the hello directory, let's create three new files: a folder named one and two files named girl and boy.

Using readdir() system call function is as follows.

/*
 ** Made by BadproG.com
 */

#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>
#include <errno.h>
#include <string.h>

int main(int c, char *v[]) {
    DIR *myDirectory;
    struct dirent *myFile;

    if (c == 2) {
        myDirectory = opendir(v[1]);
        if (myDirectory) {
            puts("OK the directory is opened, let's see its files:");
            while ((myFile = readdir(myDirectory)))
                printf("%s\n", myFile->d_name);
            /*
             ** closedir
             */
            if (closedir(myDirectory) == 0)
                puts("The directory is now closed.");
            else
                puts("The directory can not be closed.");
        } else if (errno == ENOENT)
            puts("This directory does not exist.");
        else if (errno == ENOTDIR)
            puts("This file is not a directory.");
        else if (errno == EACCES)
            puts("You do not have the right to open this folder.");
        else
            puts("That's a new error, check the manual.");
    } else
        puts("Sorry we need exactly 2 arguments.");
    return (0);
}

Let's compile this code:

$ gcc main.c

Then let's execute it:

$ ./a.out hello

All files in the hello directory appear and we finish by closing the directory stream with the closedir() system call function.

 

Comments

Comment: 

Thanks for sharing this. I used this with my own small program. You might want to add last "}" for ending main program.

Comment: 

Janne,

Thank you for your comment.

Indeed you're absolutely right.
The brace was missing.
I've modified it, many thanks. laugh

 

Add new comment

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.