Next: list_c.c Up: Program Listings Previous: cdir.c

list.c


/* list.c -  C version of a simple UNIX ls utility */

/* c89 list.c -o list */

/* need types.h and dir.h for definitions of scandir and alphasort */
#include <sys/types.h>
#include <sys/dir.h>

/* definition for getwd ie MAXPATHLEN etc */
#include <sys/param.h>

#include <stdio.h>

#define FALSE 0
#define TRUE !FALSE

/* prototype std lib functions */
extern  int alphasort();

/* variable to store current path */
char pathname[MAXPATHLEN];

main()
{ int count,i;
  struct direct **files;
  int file_select();

  if (getwd(pathname) == NULL )
   { printf("Error getting path\n);
     exit(1);
   }
  printf("Current Working Directory = %s\n",pathname);

  count = 
    scandir(pathname, &files, file_select, alphasort);


  /* If no files found, make a non-selectable menu item */
  if (count <= 0) {
    printf("No files in this directory\n");
    exit(0);
  }

  printf("Number of files = %d\n",count);

  for (i=1;i<count+1;++i)
   { printf("%s   ",files[i-1]->d_name);
     if ( (i % 4) == 0) printf("\n");
   }
   
  printf("\n"); /* flush buffer */
}


int
file_select(struct direct   *entry)
{  /* ignore . and .. entries */
      if ((strcmp(entry->d_name, ".") == 0) ||
	    (strcmp(entry->d_name, "..") == 0))
		return (FALSE); 
     else
       return (TRUE);
}


Dave.Marshall@cm.cf.ac.uk
Wed Sep 14 10:06:31 BST 1994