1 /*
2 ** Enumerate devices, directories and files.
3 **
4 ** 2012-10-15, Oliver Schmidt (ol.sc@web.de)
5 **
6 */
7 
8 
9 
10 #include <stdio.h>
11 #include <string.h>
12 #include <unistd.h>
13 #include <stdlib.h>
14 #include <device.h>
15 #include <dirent.h>
16 #include <cc65.h>
17 
18 
printdir(char * newdir)19 void printdir (char *newdir)
20 {
21     char olddir[FILENAME_MAX];
22     char curdir[FILENAME_MAX];
23     DIR *dir;
24     struct dirent *ent;
25     char *subdirs = NULL;
26     unsigned dirnum = 0;
27     unsigned num;
28 
29     getcwd (olddir, sizeof (olddir));
30     if (chdir (newdir)) {
31 
32         /* If chdir() fails we just print the
33         ** directory name - as done for files.
34         */
35         printf ("  Dir  %s\n", newdir);
36         return;
37     }
38 
39     /* We call getcwd() in order to print the
40     ** absolute pathname for a subdirectory.
41     */
42     getcwd (curdir, sizeof (curdir));
43     printf (" Dir %s:\n", curdir);
44 
45     /* Calling opendir() always with "." avoids
46     ** fiddling around with pathname separators.
47     */
48     dir = opendir (".");
49     while (ent = readdir (dir)) {
50 
51         if (_DE_ISREG (ent->d_type)) {
52             printf ("  File %s\n", ent->d_name);
53             continue;
54         }
55 
56         /* We defer handling of subdirectories until we're done with the
57         ** current one as several targets don't support other disk i/o
58         ** while reading a directory (see cc65 readdir() doc for more).
59         */
60         if (_DE_ISDIR (ent->d_type)) {
61             subdirs = realloc (subdirs, FILENAME_MAX * (dirnum + 1));
62             strcpy (subdirs + FILENAME_MAX * dirnum++, ent->d_name);
63         }
64     }
65     closedir (dir);
66 
67     for (num = 0; num < dirnum; ++num) {
68         printdir (subdirs + FILENAME_MAX * num);
69     }
70     free (subdirs);
71 
72     chdir (olddir);
73 }
74 
75 
main(void)76 void main (void)
77 {
78     unsigned char device;
79     char devicedir[FILENAME_MAX];
80 
81     /* Calling getfirstdevice()/getnextdevice() does _not_ turn on the motor
82     ** of a drive-type device and does _not_ check for a disk in the drive.
83     */
84     device = getfirstdevice ();
85     while (device != INVALID_DEVICE) {
86         printf ("Device %d:\n", device);
87 
88         /* Calling getdevicedir() _does_ check for a (formatted) disk in a
89         ** floppy-disk-type device and returns NULL if that check fails.
90         */
91         if (getdevicedir (device, devicedir, sizeof (devicedir))) {
92             printdir (devicedir);
93         } else {
94             printf (" N/A\n");
95         }
96 
97         device = getnextdevice (device);
98     }
99 
100     if (doesclrscrafterexit ()) {
101         getchar ();
102     }
103 }
104