Skip to content

Commit 8c6b125

Browse files
committed
change readdir to scandir
1 parent 5343ac2 commit 8c6b125

File tree

1 file changed

+15
-34
lines changed

1 file changed

+15
-34
lines changed

kfc.c

Lines changed: 15 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -10,15 +10,14 @@
1010
#include <unistd.h>
1111
#include "kfc.h"
1212

13-
struct dirent *de;
13+
struct dirent **de;
1414

1515
static int i, cval, randf;
1616
static int rflag, lflag, pflag = 0; /* argument flags */
1717
static size_t len = BUFF;
1818
static char *line, *sval, *mode, *conf, *evar, *eval, *seq = NULL;
1919
static char sel[BUFF];
2020
static FILE *fp;
21-
static DIR *dr;
2221

2322
static void
2423
find_palettes(void)
@@ -68,56 +67,38 @@ select_palette(void)
6867
static void
6968
list_palette(void)
7069
{
71-
dr = opendir(sel);
70+
int n = scandir(sel, &de, NULL, alphasort);
7271

73-
if ( dr == NULL )
72+
while (n--)
7473
{
75-
fprintf(stderr, "Could not open directory\n");
76-
exit(1);
77-
}
78-
79-
while( (de = readdir(dr)) != NULL )
80-
{
81-
if ( de->d_type == 8 )
74+
if (de[n]->d_type == 8)
8275
{
83-
printf("%s/%s\n", mode, de->d_name);
76+
printf("%s/%s\n", mode, de[n]->d_name);
8477
}
8578
}
8679

87-
closedir(dr);
80+
free(de);
8881
}
8982

9083
static void
9184
random_palette(void)
9285
{
93-
dr = opendir(sel);
86+
int n = scandir(sel, &de, NULL, alphasort);
9487
randf = 0;
9588

96-
if ( dr == NULL )
97-
{
98-
fprintf(stderr, "Could not open directory\n");
99-
exit(1);
100-
}
101-
102-
while( (de = readdir(dr)) != NULL )
103-
{
104-
randf++;
105-
}
106-
107-
closedir(dr);
10889
srand(time(0));
109-
i = (rand() % (randf - 0 + 1)) + 0;
110-
randf = 0;
111-
dr = opendir(sel);
112-
while( (de = readdir(dr)) != NULL )
90+
i = (rand() % (n - 0 + 1)) + 0;
91+
92+
while(n--)
11393
{
11494
if (i == randf)
11595
{
11696
strcat(sel, "/");
117-
strcat(sel, de->d_name);
97+
strcat(sel, de[n]->d_name);
11898
}
11999
randf++;
120100
}
101+
free(de);
121102
}
122103

123104
static void
@@ -157,14 +138,14 @@ usage: kfc [-L] [-r|-s palette] [-l|-p|-v]\n \
157138
int
158139
main(int argc, char **argv)
159140
{
141+
extern char *optarg;
142+
extern int optind, optopt;
143+
160144
if (argc == 1)
161145
{
162146
fprintf(stderr, "No argument(s) provided\n");
163147
exit(1);
164148
}
165-
166-
extern char *optarg;
167-
extern int optind, optopt;
168149

169150
mode = "dark";
170151

0 commit comments

Comments
 (0)