Skip to main content

ProwessApps

Learn · Practice · Excel

C Program to List Files in current Directory

C Code Example — File Handling Programs

ADVERTISEMENT

C Program to List Files in current Directory

Objective

Write a C program to list all files in the current directory.

Algorithm / Approach

  1. Include <dirent.h>.
  2. Declare a directory pointer DIR *d and a directory entry structure struct dirent *dir.
  3. Open the current directory using d = opendir(".").
  4. Use a while loop to read directory entries: (dir = readdir(d)) != NULL.
  5. Print the file name: printf("%s\n", dir->d_name).
  6. Close the directory using closedir(d).
main.c
#include<dirent.h>
#include<stdio.h> 
int main( ) {
 DIR *d;
 struct dirent *dir;
 d = opendir(".");
 if (d) {
  while ((dir = readdir(d)) != NULL) {
   printf("%s\n", dir->d_name);
  }
  closedir(d);
  }
 return 0;
}

Expected Output

first.txt
prowess.txt
second.txt

Explanation of the Program

  • C isn't just for processing data; it can interact directly with the Operating System's filesystem.
  • The dirent.h header provides POSIX standard functions for directory traversal. The string "." is a universal filesystem shortcut that refers to the "Current Working Directory" (the folder where the C program is currently running from).

Complexity

Time Complexity O(n) - Where n is the number of files in the folder.
Space Complexity O(1)
ADVERTISEMENT