C Program to List All Files in a Directory

Listing all files in a directory is a very common programming requirement. Here we’ll see how to read and display all file names in a directory using C directory entry (dirent) library.

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

int main(void) {
  DIR *dir;
  struct dirent *entry;
  dir = opendir(".");
  if (dir == NULL) {
    printf("Failed to open directory.\n");
    return 1;
  }
  while ((entry = readdir(dir)) != NULL) {
    if(entry->d_type != DT_DIR) {
      printf("%s\n", entry->d_name);
    }
  }
  closedir(dir);
  return 0;
}

This program first opens the current directory (“.”) using opendir() function. In a loop, each entry in the directory is read using readdir() function and printed if its type is not directory.

$ ls
 file1.txt  file2.txt  file3.txt  subdir1  subdir2

The current directory above contains 3 text files and two subdirectories. If we run our program in this directory, we’ll see the following output.

$ ./test
 file1.txt
 file2.txt
 file3.txt

This output does not contain the files of the subdirectories.

Read also: List all files including subdirectories.

Author: Srikanta

I write here to help the readers learn and understand computer programing, algorithms, networking, OS concepts etc. in a simple way. I have 20 years of working experience in computer networking and industrial automation.


If you also want to contribute, click here.

Leave a Reply

Your email address will not be published. Required fields are marked *

0
0
0
0
0
0