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