opendir, wopendir

From RAD Studio
Jump to: navigation, search

Go Up to dirent.h Index

Header File


dirent.h

Category

Directory Control Routines

Prototype

DIR *opendir(const char *dirname);

wDIR *wopendir(const wchar_t *dirname);

Description

Opens a directory stream for reading.

opendir is available on POSIX-compliant UNIX systems.

The opendir function opens a directory stream for reading. The name of the directory to read is dirname. The stream is set to read the first entry in the directory.

A directory stream is represented by the DIR structure, defined in dirent.h. This structure contains no user-accessible fields. Multiple directory streams can be opened and read simultaneously. Directory entries can be created or deleted while a directory stream is being read.

Use the readdir function to read successive entries from a directory stream. Use the closedir function to remove a directory stream when it is no longer needed.

Return Value

On success, opendir returns a pointer to a directory stream that can be used in calls to readdir, rewinddir, and closedir.

On error (If the directory cannot be opened), the functino returns NULL and sets the global variable errno to

ENOENT

The directory does not exist

ENOMEM

Not enough memory to allocate a DIR object



Example

 /* opendir.c - test opendir(), readdir(), closedir() */

#include <dirent.h>
#include <stdio.h>
#include <stdlib.h>

void scandir(char *dirname)
{
   DIR *dir;
   struct dirent *ent;

   printf("First pass on '%s':\n",dirname);
   if ((dir = opendir(dirname)) == NULL)
   {
     perror("Unable to open directory");
     exit(1);
   }
   while ((ent = readdir(dir)) != NULL)
     printf("%s\n",ent->d_name);

   printf("Second pass on '%s':\n",dirname);
   rewinddir(dir);
   while ((ent = readdir(dir)) != NULL)
     printf("%s\n",ent->d_name);
   if (closedir(dir) != 0)
     perror("Unable to close directory");
}

void main(int argc,char *argv[])
{
   if (argc != 2)
   {
     printf("usage: opendir dirname\n");
     exit(1);
   }
   scandir(argv[1]);
   exit(0);
}

Portability

POSIX Win32 ANSI C ANSI C++

opendir

+

+

wopendir