Add helper mg_fs_ls()

This commit is contained in:
Sergey Lyubka 2024-02-01 17:45:20 +00:00
parent f8898b016e
commit cbfa57a955
4 changed files with 42 additions and 0 deletions

View File

@ -1666,6 +1666,26 @@ bool mg_file_printf(struct mg_fs *fs, const char *path, const char *fmt, ...) {
return result;
}
// This helper function allows to scan a filesystem in a sequential way,
// without using callback function:
// char buf[100] = "";
// while (mg_fs_ls(&mg_fs_posix, "./", buf, sizeof(buf))) {
// ...
static void mg_fs_ls_fn(const char *filename, void *param) {
struct mg_str *s = (struct mg_str *) param;
if (s->ptr[0] == '\0') {
mg_snprintf((char *) s->ptr, s->len, "%s", filename);
} else if (strcmp(s->ptr, filename) == 0) {
((char *) s->ptr)[0] = '\0'; // Fetch next file
}
}
bool mg_fs_ls(struct mg_fs *fs, const char *path, char *buf, size_t len) {
struct mg_str s = {buf, len};
fs->ls(path, mg_fs_ls_fn, &s);
return buf[0] != '\0';
}
#ifdef MG_ENABLE_LINES
#line 1 "src/fs_fat.c"
#endif

View File

@ -1025,6 +1025,7 @@ struct mg_fd {
struct mg_fd *mg_fs_open(struct mg_fs *fs, const char *path, int flags);
void mg_fs_close(struct mg_fd *fd);
bool mg_fs_ls(struct mg_fs *fs, const char *path, char *buf, size_t len);
char *mg_file_read(struct mg_fs *fs, const char *path, size_t *size);
bool mg_file_write(struct mg_fs *fs, const char *path, const void *, size_t);
bool mg_file_printf(struct mg_fs *fs, const char *path, const char *fmt, ...);

View File

@ -72,3 +72,23 @@ bool mg_file_printf(struct mg_fs *fs, const char *path, const char *fmt, ...) {
free(data);
return result;
}
// This helper function allows to scan a filesystem in a sequential way,
// without using callback function:
// char buf[100] = "";
// while (mg_fs_ls(&mg_fs_posix, "./", buf, sizeof(buf))) {
// ...
static void mg_fs_ls_fn(const char *filename, void *param) {
struct mg_str *s = (struct mg_str *) param;
if (s->ptr[0] == '\0') {
mg_snprintf((char *) s->ptr, s->len, "%s", filename);
} else if (strcmp(s->ptr, filename) == 0) {
((char *) s->ptr)[0] = '\0'; // Fetch next file
}
}
bool mg_fs_ls(struct mg_fs *fs, const char *path, char *buf, size_t len) {
struct mg_str s = {buf, len};
fs->ls(path, mg_fs_ls_fn, &s);
return buf[0] != '\0';
}

View File

@ -39,6 +39,7 @@ struct mg_fd {
struct mg_fd *mg_fs_open(struct mg_fs *fs, const char *path, int flags);
void mg_fs_close(struct mg_fd *fd);
bool mg_fs_ls(struct mg_fs *fs, const char *path, char *buf, size_t len);
char *mg_file_read(struct mg_fs *fs, const char *path, size_t *size);
bool mg_file_write(struct mg_fs *fs, const char *path, const void *, size_t);
bool mg_file_printf(struct mg_fs *fs, const char *path, const char *fmt, ...);