Follow Techotopia on Twitter

On-line Guides
All Guides
eBook Store
iOS / Android
Linux for Beginners
Office Productivity
Linux Installation
Linux Security
Linux Utilities
Linux Virtualization
Linux Kernel
System/Network Admin
Programming
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Databases
Mail Systems
openSolaris
Eclipse Documentation
Techotopia.com
Virtuatopia.com
Answertopia.com

How To Guides
Virtualization
General System Admin
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Windows
Problem Solutions
Privacy Policy

  




 

 

14.2.4 Simple Program to List a Directory

Here's a simple program that prints the names of the files in the current working directory:

     #include <stddef.h>
     #include <stdio.h>
     #include <sys/types.h>
     #include <dirent.h>
     
     int
     main (void)
     {
       DIR *dp;
       struct dirent *ep;
     
       dp = opendir ("./");
       if (dp != NULL)
         {
           while (ep = readdir (dp))
             puts (ep->d_name);
           (void) closedir (dp);
         }
       else
         perror ("Couldn't open the directory");
     
       return 0;
     }

The order in which files appear in a directory tends to be fairly random. A more useful program would sort the entries (perhaps by alphabetizing them) before printing them; see Scanning Directory Content, and Array Sort Function.


 
 
  Published under the terms of the GNU General Public License Design by Interspire