What Functions to Use for Directory Access in C/C++

Accessing directory files is a common task for programmers. In C and C++, we use the functions opendir() and readdir() to access directories.

opendir and readdir are functions used for directory operations, commonly used to traverse the file system. Below are the core functionalities and usage methods:

opendir Function

  • Function: Opens the specified directory and returns a directory handle (DIR pointer).
  • Parameter: Directory path (e.g., const char *name).
  • Return Value: Returns a DIR pointer on success, or <span><span>NULL</span></span> on failure and sets the error code.
  • DIR *dirp = opendir("./my_dir");if (!dirp) {    perror("opendir error");    exit(EXIT_FAILURE);}

readdir Function

  • Function: Reads the filenames in the directory and returns a dirent structure pointer.
  • Parameter: Directory handle returned by opendir (<span>DIR *dirp</span>).
  • Return Value: Returns a structure pointer containing the filename (<span>d_name</span>) and type (<span>d_type</span>); returns <span>NULL</span> at the end or on error.
struct dirent *entry;while ((entry = readdir(dirp)) != NULL) {    printf("Filename: %s\n", entry->d_name);}

Generally, these two functions are used together:

Combined Usage Process

  1. Use <span><span>opendir</span></span> to open the directory.
  2. Loop to call <span><span>readdir</span></span> to read filenames until it returns <span><span>NULL</span></span>.
  3. Use <span><span>closedir</span></span> to close the directory handle.
#include "sys/types.h"#include "direct.h"#include "stdio.h"#include <dirent.h>#include <stdlib.h>int getFileNum(const char *path);int main(int argc,char *argv[]){    int num = getFileNum("E:\");    printf("The total directory numbers: %d\n", num);    return 0;}// We get the dir numbers.int getFileNum(const char *path) {    DIR *dir = opendir(path);    if (dir==NULL) {        perror("opendir");        exit(0);    }    struct dirent *ptr;    // Count the dir number.    int total =0;    while((ptr= readdir(dir)) != NULL) {        // Get directory names.        char* dname = ptr->d_name;        printf("Tell me the directory name = %s\n", dname);        // Ignore . and .., etc., blank dir        if(strcmp(dname,".")==0 || strcmp(dname,"..")==0) {            continue;        }        total ++;    }    closedir(dir);    return total;}

**Tips: Time and tide wait for no man. 岁月不待人

Leave a Comment