Added new error codes. Improved error handling.
[libgit2.git] / src / win32 / dir.c
blob069a41c3acd6dfeba2d5ebd1ce0e568d5ce3ad51
1 #define GIT__WIN32_NO_WRAP_DIR
2 #include "dir.h"
4 static int init_filter(char *filter, size_t n, const char *dir)
6 size_t len = strlen(dir);
8 if (len+3 >= n)
9 return 0;
11 strcpy(filter, dir);
12 if (len && dir[len-1] != '/')
13 strcat(filter, "/");
14 strcat(filter, "*");
16 return 1;
19 git__DIR *git__opendir(const char *dir)
21 char filter[4096];
22 git__DIR *new;
24 if (!dir || !init_filter(filter, sizeof(filter), dir))
25 return NULL;
27 new = git__malloc(sizeof(*new));
28 if (!new)
29 return NULL;
31 new->dir = git__malloc(strlen(dir)+1);
32 if (!new->dir) {
33 free(new);
34 return NULL;
36 strcpy(new->dir, dir);
38 new->h = FindFirstFile(filter, &new->f);
39 if (new->h == INVALID_HANDLE_VALUE) {
40 free(new->dir);
41 free(new);
42 return NULL;
44 new->first = 1;
46 return new;
49 struct git__dirent *git__readdir(git__DIR *d)
51 if (!d || d->h == INVALID_HANDLE_VALUE)
52 return NULL;
54 if (d->first)
55 d->first = 0;
56 else {
57 if (!FindNextFile(d->h, &d->f))
58 return NULL;
61 if (strlen(d->f.cFileName) >= sizeof(d->entry.d_name))
62 return NULL;
64 d->entry.d_ino = 0;
65 strcpy(d->entry.d_name, d->f.cFileName);
67 return &d->entry;
70 void git__rewinddir(git__DIR *d)
72 char filter[4096];
74 if (d) {
75 if (d->h != INVALID_HANDLE_VALUE)
76 FindClose(d->h);
77 d->h = INVALID_HANDLE_VALUE;
78 d->first = 0;
79 if (init_filter(filter, sizeof(filter), d->dir)) {
80 d->h = FindFirstFile(filter, &d->f);
81 if (d->h != INVALID_HANDLE_VALUE)
82 d->first = 1;
87 int git__closedir(git__DIR *d)
89 if (d) {
90 if (d->h != INVALID_HANDLE_VALUE)
91 FindClose(d->h);
92 if (d->dir)
93 free(d->dir);
94 free(d);
96 return 0;