Added dir.c
[idzebra-moved-to-github.git] / index / dir.c
1 /*
2  * Copyright (C) 1994, Index Data I/S 
3  * All rights reserved.
4  * Sebastian Hammer, Adam Dickmeiss
5  *
6  * $Log: dir.c,v $
7  * Revision 1.1  1995-09-01 10:34:51  adam
8  * Added dir.c
9  *
10  */
11 #include <stdio.h>
12 #include <assert.h>
13 #include <unistd.h>
14 #include <dirent.h>
15 #include <sys/stat.h>
16 #include <sys/types.h>
17 #include <fcntl.h>
18 #include <ctype.h>
19
20 #include <util.h>
21 #include "index.h"
22
23 struct dir_entry *dir_open (const char *rep)
24 {
25     DIR *dir;
26     struct dirent *dent;
27     size_t entry_max = 20;
28     size_t idx = 0;
29     struct dir_entry *entry;
30
31     log (LOG_DEBUG, "dir_open %s", rep);
32     if (!(dir = opendir(rep)))
33     {
34         log (LOG_WARN|LOG_ERRNO, "opendir %s", rep);
35         if (errno != ENOENT)
36             exit (1);
37         return NULL;
38     }
39     if (!(entry = malloc (sizeof(*entry) * entry_max)))
40     {
41         log (LOG_FATAL|LOG_ERRNO, "malloc");
42         exit (1);
43     }    
44     while ((dent = readdir (dir)))
45     {
46         if (idx == entry_max-1)
47         {
48             struct dir_entry *entry_n;
49
50             if (!(entry_n = malloc (sizeof(*entry) * (entry_max + 100))))
51             {
52                 log (LOG_FATAL|LOG_ERRNO, "malloc");
53                 exit (1);
54             }
55             memcpy (entry_n, entry, entry_max * sizeof(*entry));
56             free (entry);
57             entry = entry_n;
58             entry_max += 100;
59         }
60         if (!(entry[idx].name = malloc (strlen(dent->d_name)+1)))
61         {
62             log (LOG_FATAL|LOG_ERRNO, "malloc");
63             exit (1);
64         }
65         strcpy (entry[idx].name, dent->d_name);
66     }
67     entry[idx].name = NULL;
68     closedir (dir);
69     return entry;
70 }
71
72 int dir_cmp (const void *p1, const void *p2)
73 {
74     return strcmp (((struct dir_entry *) p1)->name,
75                    ((struct dir_entry *) p2)->name);
76 }
77
78 void dir_sort (struct dir_entry *e)
79 {
80     size_t nmemb = 0;
81     while (e[nmemb].name)
82         nmemb++;
83     qsort (e, nmemb, sizeof(*e), dir_cmp); 
84 }
85
86 void dir_free (struct dir_entry **e_p)
87 {
88     size_t i = 0;
89     struct dir_entry *e = *e_p;
90
91     assert (e);
92     while (e[i].name)
93         free (e[i].name);
94     free (e);
95     *e_p = NULL;
96 }