aboutsummaryrefslogtreecommitdiff
path: root/doc/d.c
blob: 51c0612d4d31e0016dd4ce5f904a7f03eea1549b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdlib.h>
#include <string.h>

/* Return true if file NAME is a directory. */
static int
isdir (char *name)
{
  struct stat st;
  
  if (stat (name, &st))
    {
      perror (name);
      return 0;
    }
  return S_ISDIR (st.st_mode);
}

static char *ignored_names[] = { ".", "..", NULL };

/* Return true if NAME should not be recursed into */
int
ignorent (char *name)
{
  char **p;
  for (p = ignored_names; *p; p++)
    if (strcmp (name, *p) == 0)
      return 1;
  return 0;
}

int max_level = -1;

/* Print contents of the directory PREFIX/NAME.
   Prefix each output line with LEVEL spaces. */
void
printdir (int level, char *name)
{
  DIR *dir;
  struct dirent *ent;
  char cwd[512];

  if (!getcwd(cwd, sizeof cwd)) 
    {
      perror ("cannot save cwd\n");
      _exit (1);
    }
  chdir (name);
  dir = opendir (".");
  if (!dir)
    {
      perror (name);
      _exit (1);
    }
  
  while ((ent = readdir (dir)))
    {
      printf ("%*.*s%s", level, level, "", ent->d_name);
      if (ignorent (ent->d_name))
        printf ("\n");
      else if (isdir (ent->d_name))
        {
          printf ("/");
          if (level + 1 == max_level)
            putchar ('\n');
          else
            {
              printf (" contains:\n");
              printdir (level + 1, ent->d_name);
            }
        }
      else
        printf ("\n");
    }
  closedir (dir);
  chdir (cwd);
}

int
main (int argc, char **argv)
{
  if (argc < 2)
    {
      fprintf (stderr, "usage: d [-MAX] DIR [DIR...]\n");
      return 1;
    }

  if (argv[1][0] == '-')
    {
      if (!(argv[1][1] == '-' && argv[1][2] == 0))
        max_level = atoi (&argv[1][1]);
      --argc;
      ++argv;
    }
  
  while (--argc)
    printdir (0, *++argv);
  
  return 1;
}

Return to:

Send suggestions and report system problems to the System administrator.