Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
emscripten-core
GitHub Repository: emscripten-core/emscripten
Path: blob/main/system/lib/html5/emscripten_wget.c
6171 views
1
#include <emscripten.h>
2
#include <errno.h>
3
#include <fcntl.h>
4
#include <string.h>
5
#include <sys/stat.h>
6
#include <unistd.h>
7
8
// Creates all ancestor directories of a given file, if they do not already
9
// exist. Returns 0 on success or 1 on error.
10
static int mkdirs(const char* file) {
11
char* copy = strdup(file);
12
char* c = copy;
13
while (*c) {
14
// Create any non-trivial (not the root "/") directory.
15
if (*c == '/' && c != copy) {
16
*c = 0;
17
int result = mkdir(copy, S_IRWXU);
18
*c = '/';
19
// Continue while we succeed in creating directories or while we see that
20
// they already exist.
21
if (result < 0 && errno != EEXIST) {
22
free(copy);
23
return 1;
24
}
25
}
26
c++;
27
}
28
free(copy);
29
return 0;
30
}
31
32
int emscripten_wget(const char* url, const char* file) {
33
// Create the ancestor directories.
34
if (mkdirs(file)) {
35
return 1;
36
}
37
38
// Fetch the data.
39
void* buffer;
40
int num;
41
int error;
42
emscripten_wget_data(url, &buffer, &num, &error);
43
if (error) {
44
return 1;
45
}
46
47
// Write the data.
48
int fd = open(file, O_WRONLY | O_CREAT, S_IRWXU);
49
if (fd >= 0) {
50
write(fd, buffer, num);
51
close(fd);
52
}
53
free(buffer);
54
return fd < 0;
55
}
56
57