Home
 
 
Search:  
C C++ Perl PHP Python HTML ShellScripts
 
 
  Coding Books
  Tutorials
  Search Code
  Browse Code
  Link to Us
  Site News
  Contact Metalshell
 
 
 
  Submit Code   Statistics
 



Gcc Target Description Macros: Using and Porting the Gnu Compiler Collection Gcc    (ISBN: 0595100384)


 

 List Price: $14.95
 Our Price: $14.95
 Used Price:

 Release Date: August, 1900
 Manufacturer: iUniverse.com (Paperback)
 Sales Rank: 535,117

 Author: Richard M. Stallman









More Info

 Read Directory 2003-06-06 22:44:44
 
Category: source:c:linux
Description: Example on using opendir, closedir, and readdir to open a directory stream and read in and print file names.
Platform: linux
Author: mind
Viewed: 16652
Rating: 4.6/5 (183 votes)
If you have any questions about this piece of code or still need help, try posting your question on the forum.

 

Printable Version
openreaddir.c
/* openreaddir.c by mind [mind@metalshell.com]
 *
 * Example on using opendir, closedir, and readdir to open a directory
 * stream and read in and print file names.
 *
 * 06/04/03
 *
 * http://www.metalshell.com/
 *
 */

#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>
#include <errno.h>

int main(int argc, char *argv[])
{
        DIR             *dip;
        struct dirent   *dit;

        int             i = 0;

        /* check to see if user entered a directory name */
        if (argc < 2)
        {
                printf("Usage: %s <directory>\n", argv[0]);
                return 0;
        }

        /* DIR *opendir(const char *name);
         *
         * Open a directory stream to argv[1] and make sure
         * it's a readable and valid (directory) */
        if ((dip = opendir(argv[1])) == NULL)
        {
                perror("opendir");
                return 0;
        }

        printf("Directory stream is now open\n");

        /*  struct dirent *readdir(DIR *dir);
         *
         * Read in the files from argv[1] and print */
        while ((dit = readdir(dip)) != NULL)
        {
                i++;
                printf("\n%s", dit->d_name);
        }

        printf("\n\nreaddir() found a total of %i files\n", i);

        /* int closedir(DIR *dir);
         *
         * Close the stream to argv[1]. And check for errors. */
        if (closedir(dip) == -1)
        {
                perror("closedir");
                return 0;
        }

        printf("\nDirectory stream is now closed\n");
        return 1;
}
Rate this code:
(Not Helpful)  (Very Helpful) 

 
 
   Developer.*  
   Blue Parrots  
   Technipal  
   Defy Magazine  
   Code Project  
   Prog. Heaven  


Got Money?