/* dirprt.c      dirprt  <directory>                                  */
/* Just read and print the directory                                  */
/* The command line gives the starting directory                      */
/* Not quite portable because it has to get info from a directory     */
/* Not quite ANSI X3.159-1989, ANSI STD C because of second #include  */

#include <ctype.h>
#include <sys/stat.h>
#include <dirent.h>
#include <stddef.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

static void  read_dir(char *local_dir);

char    top_dir[1024];
int     if_files=0;
struct stat buf;
int     if_status=0;

int main( int argc, char *argv[] )
{
  char users_cwd[1024];
  char yn;
  int     i;

  strcpy(top_dir,argv[1]);

  if(chdir(top_dir) != 0)
  { 
    printf("Not a valid directory from here. \n");
    exit(1);
  }
  getcwd(top_dir,1023); /* normalized form */
  printf("%s directory to be printed \n", top_dir);
  lstat(top_dir,&buf); /* get device number */

  read_dir(top_dir); /* read and print directory */

  return 0;
} /* end of dirprt main */


static void read_dir(char *local_dir)
{
  DIR *dirp;
  struct dirent *dp;
  long status;
  char temp_dir[1024];
  char short_dir[64];
  long local_files=0;
  int i;


  if(chdir(local_dir) != 0)
  { 
    printf("!!! unable to get to directory |%s| \n", local_dir);
    return;
  }
  getcwd(temp_dir,1022); /* normalized form */

  dirp = opendir(temp_dir);
  for (dp = readdir(dirp); dp != NULL; dp = readdir(dirp))
  {
    status = lstat(dp->d_name, &buf);
    if(status < 0)
    {
      printf("%s %ol = = = = stat error = = = \n",dp->d_name, status);
      continue;
    }
    if((buf.st_mode & S_IFMT) == S_IFDIR) /* have a directory ! */
    {
       /* NOT certain files !!   "."  ".."  and no links */
       if(!strcmp(dp->d_name,".")) continue;
       if(!strcmp(dp->d_name,"..")) continue;
       printf("dir= %s \n", dp->d_name);
    }
    else
    {
      printf("file= %s \n", dp->d_name);
    }
  } /* end loop through this directory */

  closedir(dirp);

} /* end read_dir  */


