Hello there!
I just started a serious hobby project with ESP32 using esp-idf. This project uses SD Card for storing various data points that are organized in nested directories, and I would like to write a method similar to MakeSureDirectoryPathExists(). Basically I am looking for a function that will create all non-existing sub-directories in a directory path.
Let us say my SD Card is mounted as /sdcard, and I already have a directory in it viz., "/sdcard/data", so if I call this method with "/sdcard/data/devices/sensor1/data.csv", it should create sub-folders "devices" and "sensor1" (under respective parent directories of course). How can I do that in esp-idf? Since mine is a new project I am free to use any available library or filesystem that can make it easier to implement this function.
Thanks in advance!
How to implement MakeSureDirectoryPathExists() in esp-idf?
Re: How to implement MakeSureDirectoryPathExists() in esp-idf?
Ok... this is what I came up with. I just got mkdir() working as expected including the /sdcard mount point in the directory path.
- void MyESPApp::MakesureDirectoryPathExists(char *filePath)
- {
- char *fullPath = filePath;
- filePath++; // Skip the leading path delimiter
- while (*filePath && *filePath != '/')
- filePath++; // skip mountpoint
- while (*filePath)
- {
- if (*filePath == '/')
- {
- *filePath = '\0';
- mkdir(fullPath, 0755);
- *filePath = '/';
- }
- filePath++;
- }
- }
Re: How to implement MakeSureDirectoryPathExists() in esp-idf?
Modified the code to call mkdir only if the directory does not exist.
- void ESPApp::MakesureDirectoryPathExists(char *filePath)
- {
- char *directory = filePath;
- filePath++; // Skip the leading path delimiter
- while (*filePath && *filePath != '/')
- filePath++; // skip mountpoint
- while (*filePath)
- {
- if (*filePath == '/')
- {
- *filePath = '\0';
- //mkdir(fullPath, 0755);
- struct stat s;
- bool directory_exists = stat(directory, &s) == 0;
- if (!directory_exists)
- {
- if (mkdir(directory, 0775) != 0)
- {
- ESP_LOGE(TAG, "mkdir failed with error: %s\n", strerror(errno));
- }
- }
- *filePath = '/';
- }
- filePath++;
- }
- }
-
- Posts: 1708
- Joined: Mon Oct 17, 2022 7:38 pm
- Location: Europe, Germany
Who is online
Users browsing this forum: No registered users and 118 guests