Listing 4 List entries in the current directory

/* list.c: Print a directory listing */

#include <stdio.h>
#include <dirent.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <time.h>
#include <string.h>
#include <assert.h>

static char *attr_str(short attr);

main()
{
   DIR *dirp = opendir(".");  /* Current dir */
   struct dirent *entry;
   struct stat finfo;

   assert(dirp);
   while ((entry = readdir(dirp)) != NULL)
   {
      stat(entry->d_name,&finfo);
      printf(
            "%-12.12s %s %8ld %s",
            strlwr(entry->d_name),
            attr_str(finfo.st_mode),
            finfo.st_size,
            ctime(&finfo.st_mtime)
           );
   }
   closedir(dirp);
   return 0;
}

static char *attr_str(short attr)
{
   static char s[4];

   strcpy(s,"---");
   if (attr & S_IFDIR)
      s[0] = 'd';
   if (attr & S_IREAD)
      s[1] = 'r';
   if (attr & S_IWRITE)
      s[2] = 'w';
   return s;
}

/* End of File */