Home  >  Article  >  Backend Development  >  How to get a list of files in a directory using C or C++?

How to get a list of files in a directory using C or C++?

WBOY
WBOYforward
2023-09-22 13:53:15585browse

How to get a list of files in a directory using C or C++?

Let us consider the following C example code to get the list of files in a directory.

Algorithm

Begin
   Declare a poniter dr to the DIR type.
   Declare another pointer en of the dirent structure.
   Call opendir() function to open all file in present directory.
   Initialize dr pointer as dr = opendir(".").
   If(dr)
      while ((en = readdir(dr)) != NULL)
         print all the file name using en->d_name.
      call closedir() function to close the directory.
End.

Example

#include <iostream>
#include <dirent.h>
#include <sys/types.h>
using namespace std;
int main(void) {
   DIR *dr;
   struct dirent *en;
   dr = opendir("."); //open all directory
   if (dr) {
      while ((en = readdir(dr)) != NULL) {
         cout<<" \n"<<en->d_name; //print all directory name
      }
      closedir(dr); //close all directory
   }
   return(0);
}

Output

BINSEARC.C
BINTREE (1).C
BINTREE.C
BTREE.C
BUBBLE.C
c.txt
file3.txt
HEAP.C
HEAPSORT.C
HLINKLST.C
INSERTIO.C
LINKLIST.C
LINKLST.C
LLIST1.C
players.cpp
PolarRect.cpp
QUEUE.C

Example

#include <stdio.h>
#include <dirent.h>
int main(void) {
   DIR *dr;
   struct dirent *en;
   dr = opendir("."); //open all or present directory
   if (dr) {
      while ((en = readdir(dr)) != NULL) {
         printf("%s\n", en->d_name); //print all directory name
      }
      closedir(dr); //close all directory
   }
   return(0);
}

Output

BINSEARC.C
BINTREE (1).C
BINTREE.C
BTREE.C
BUBBLE.C
c.txt
file3.txt
HEAP.C
HEAPSORT.C
HLINKLST.C
INSERTIO.C
LINKLIST.C
LINKLST.C
LLIST1.C

The above is the detailed content of How to get a list of files in a directory using C or C++?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete