Back

#include<stdio.h>
#include<string.h>
#include<fcntl.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<sys/dir.h>
#include "dirent.h"

void fsize1(char *name);
void dirwalk(char *dir, void (*fcn)(char *));

int main(int argc, char **argv)
{
  if (argc==1) fsize1(".");
  else
   while (--argc > 0)
     fsize1(*++argv);
  return 0;
}

void fsize1(char *name)
{
  struct stat stbuf;

  if (stat(name, &stbuf) == -1)
    {
      fprintf(stderr, "fsize: can't access %s\n", name);
      return;
    }
  if ((stbuf.st_mode & S_IFMT) == S_IFDIR)
    dirwalk(name, fsize1);
  printf("%8ld %s\n", stbuf.st_size, name);
}


void dirwalk(char *dir, void (*fcn)(char *))
{
  char name[MAX_PATH1];
  Dirent *dp;
  DIR1 *dfd;

  if ((dfd = opendir1(dir)) == NULL)
   {
     fprintf(stderr, "dirwalk: can't open %s\n", dir);
     return;
   }

  while ((dp = readdir1(dfd)) != NULL)
    {
      if (strcmp(dp->name, ".") == 0 || strcmp(dp->name, "..")) continue;
      if (strlen(dir) + strlen(dp->name) +2 > sizeof(name))
         fprintf(stderr, "dirwalk: name %s %s too lone\n", dir, dp->name);
      else
       {
         sprintf(name, "%s/%s", dir, dp->name);
         (*fcn)(name);
    }
  }

closedir1(dfd);
}

DIR1 *opendir1(char *dirname)
{
   int fd;
   struct stat stbuf;
   DIR1 *dp;

   if ((fd = open(dirname, O_RDONLY, 0)) == -1 || fstat(fd, &stbuf) == -1 ||
        (stbuf.st_mode & S_IFMT) != S_IFDIR || (dp = (DIR1 *) malloc(sizeof(DIR1))) == NULL)
       return NULL;
   dp->fd = fd;
   return dp;
}

void closedir1(DIR1 *dp)
{
  if (dp)
   {
     close(dp->fd);
     free(dp);
   }
}

Dirent *readdir1(DIR1 *dp)
{
  struct direct dirbuf;
  static Dirent d;

  while (read(dp->fd, (char *) &dirbuf, sizeof(dirbuf)) == sizeof(dirbuf))
    {
      if (dirbuf.d_ino ==0) continue;
      d.ino = dirbuf.d_ino;
      strncpy(d.name, dirbuf.d_name, DIRSIZ);
      d.name[DIRSIZ] = '\0';
      return &d;
   }
 return NULL;
}

Top