Write a C program to print all files and folders.

In C programming, we can list all files and folders in a directory using directory handling functions. This requires the dirent.h header which provides structures and functions to work with directory entries.

Syntax

DIR *opendir(const char *dirname);
struct dirent *readdir(DIR *dirp);
int closedir(DIR *dirp);

Key Functions

  • opendir() − Opens a directory stream for reading
  • readdir() − Reads directory entries one by one
  • closedir() − Closes the directory stream

Note: This program uses dirent.h which is POSIX standard. On Windows with certain compilers, you might need additional setup or use platform-specific alternatives.

Example

Following is the C program for printing all files and folders in the current directory −

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

int main() {
    struct dirent *d;
    DIR *dr;
    
    dr = opendir(".");
    
    if(dr != NULL) {
        printf("List of Files & Folders:
"); printf("-------------------------
"); while((d = readdir(dr)) != NULL) { printf("%s
", d->d_name); } closedir(dr); } else { printf("Error: Could not open directory!
"); } return 0; }

How It Works

  1. opendir(".") opens the current directory ("." represents current directory)
  2. readdir() reads each directory entry sequentially until it returns NULL
  3. d->d_name contains the name of each file or folder
  4. closedir() releases the directory stream resources

Sample Output

List of Files & Folders:
-------------------------
.
..
program.c
data.txt
folder1
image.jpg
script.py

Key Points

  • The entries "." and ".." represent current and parent directories respectively
  • Always check if opendir() returns NULL to handle errors
  • Remember to call closedir() to free system resources
  • The order of files listed depends on the filesystem implementation

Conclusion

Using dirent.h functions, we can easily traverse directory contents in C. This approach provides a portable way to list files and folders across different Unix-like systems.

Updated on: 2026-03-15T13:59:04+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements