[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Bug#12411: glibc-doc: new directory listing program



Attached is my attempt at writing a clear, yet succinct example for
reading directory listings using opendir/readdir/closedir. I think mine
is easier to follow (a more straightforward structure), but I'd be happy
enough with the patch by H. S. Teoh.

Once sarge is released and new libc packages can be developed again, I
rather think it would be good to finally fix and close this 7 year old
bug. :)

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

int
main (void)
{
  DIR *dp;
  struct dirent *ep;

  /* Open directory, check for errors.  */
  dp = opendir ("./");
  if (dp == NULL)
    {
      perror ("Couldn't open the directory");
      return 1;
    }

  /* Read directory until it ends or there is an error.  */
  while ((ep = readdir (dp)) != NULL)
    (void) puts (ep->d_name); /* In this example, we ignore puts failure.  */

  /* Check for error reading directory. EBADF is the only documented one.  */
  if (errno == EBADF)
    {
      perror ("Couldn't read directory");
      return 1;
    }
    
  /* Close directory, check for errors.  */
  if (closedir (dp) == -1)
    {
      perror ("Couldn't close the directory");
      return 1;
    }
  
  return 0;
}

Reply to: