]> git.lizzy.rs Git - nothing.git/blob - src/system/file.c
adc9acad6942954a7704ff3a1c6672f526cc7afd
[nothing.git] / src / system / file.c
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <errno.h>
4
5 #include "file.h"
6 #include "system/nth_alloc.h"
7 #include "system/stacktrace.h"
8 #include "lt_adapters.h"
9
10 #ifdef _WIN32
11
12 struct DIR
13 {
14     HANDLE hFind;
15     WIN32_FIND_DATA data;
16     struct dirent *dirent;
17 };
18
19 DIR *opendir(const char *dirpath)
20 {
21     trace_assert(dirpath);
22
23     char buffer[MAX_PATH];
24     snprintf(buffer, MAX_PATH, "%s\\*", dirpath);
25
26     DIR *dir = nth_calloc(1, sizeof(DIR));
27
28     dir->hFind = FindFirstFile(buffer, &dir->data);
29     if (dir->hFind == INVALID_HANDLE_VALUE) {
30         goto fail;
31     }
32
33     return dir;
34
35 fail:
36     if (dir) {
37         free(dir);
38     }
39
40     return NULL;
41 }
42
43 struct dirent *readdir(DIR *dirp)
44 {
45     trace_assert(dirp);
46
47     if (dirp->dirent == NULL) {
48         dirp->dirent = nth_calloc(1, sizeof(struct dirent));
49     } else {
50         if(!FindNextFile(dirp->hFind, &dirp->data)) {
51             return NULL;
52         }
53     }
54
55     memset(dirp->dirent->d_name, 0, sizeof(dirp->dirent->d_name));
56
57     strncpy(
58         dirp->dirent->d_name,
59         dirp->data.cFileName,
60         sizeof(dirp->dirent->d_name) - 1);
61
62     return dirp->dirent;
63 }
64
65 void closedir(DIR *dirp)
66 {
67     trace_assert(dirp);
68
69     FindClose(dirp->hFind);
70     if (dirp->dirent) {
71         free(dirp->dirent);
72     }
73     free(dirp);
74 }
75
76 #endif
77
78 String read_whole_file(const char *filepath)
79 {
80     trace_assert(filepath);
81
82     String result = string(0, NULL);
83     FILE *f = fopen(filepath, "rb");
84     if (!f) goto end;
85     if (fseek(f, 0, SEEK_END) < 0) goto end;
86     long m = ftell(f);
87     if (m < 0) goto end;
88     result.count = (size_t) m;
89     char *buffer = nth_calloc(1, result.count);
90     size_t n = fread(buffer, 1, result.count, f);
91     trace_assert(n == result.count);
92     result.data = buffer;
93
94 end:
95     if (f) fclose(f);
96     return result;
97 }