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