closedir() — Close a directory

Standards

Standards / Extensions C or C++ Dependencies

POSIX.1
XPG4
XPG4.2
Single UNIX Specification, Version 3

both  

Format

#define _POSIX_SOURCE
#include <dirent.h>

int closedir(DIR *dir);

General description

Closes the directory indicated by dir. It frees the buffer that readdir() uses when reading the directory stream.

Returned value

If successful, closedir() returns 0.

If unsuccessful, closedir() returns -1 and sets errno to one of the following values:
Error Code
Description
EBADF
dir does not refer to an open directory stream.
EINTR
closedir() was interrupted by a signal. The directory may or may not be closed.

Example

CELEBC18
⁄* CELEBC18

   This example closes a directory.

 *⁄
#define _POSIX_SOURCE
#include <dirent.h>
#include <sys⁄types.h>
#undef _POSIX_SOURCE
#include <stdio.h>

main() {
  DIR *dir;
  struct dirent *entry;
  int count;

  if ((dir = opendir("⁄")) == NULL)
    perror("opendir() error");
  else {
    count = 0;
    while ((entry = readdir(dir)) != NULL) {
      printf("directory entry %03d: %s\n", ++count, entry->d_name);
    }
    closedir(dir);
  }
}
Output
directory entry 001: .
directory entry 002: ..
directory entry 003: bin
directory entry 004: dev
directory entry 005: etc
directory entry 006: lib
directory entry 007: tmp
directory entry 008: u
directory entry 009: usr

Related information