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