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

The opendir() system call function is used to open a directory and to return a pointer on this directory.
Let's take an example of the using of the opendir system call function.

First, we have to create two files: a directory named hello and file name world.

mkdir hello
touch world

And now let's create the main.c file:

/*
** Made by BadproG.com
*/

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

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

  myDirectory = opendir(v[1]);
  if (c == 2)
    {
      if (myDirectory)
        {
          puts("OK the folder is opened.");
          /*                                                                           
          ** 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 try:

$ gcc main.c

then let's try to open different files and see what is happening:

$ ./a.out hello
$ ./a.out world
$ ./a.out earth

Now try to remove all access to the hello directory:

$ chmod 000 hello

and try to reopen it:

$ gcc main.c && ./a.out hello

The code of main.c tests if there are exactly two arguments.
Then it tests if the second argument (v[1]) exist.
If yes, it opens it or it returns a POSIX error with the famous errno() system call function.

You can add more errors for the opendir() function such as EMFILE, ENFILE or ENOMEM.
To finish do not forget that an opened directory stream has always to be closed.

Add new comment

Plain text

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