Basic file operations not working as expected when using SPIFFS
Posted: Wed Oct 18, 2023 2:38 pm
Hi,
I am currently building a ESP-IDF project using SPIFFS to store various files.
It's mostly going as expected, but I noticed some anomalies.
Reading and writing the files with fopen, fread and fwrite works fine.
While implementing a initial test to check if the file exists and write a blank file if it doesn't I realized, that the access() function always returns -1 to signal the file does not exist. I literally open it with fopen in read mode and the pointer is not NULL, still access returns an error.
Don't I have the permission to check for existence?
Here is the code in question:
I am currently building a ESP-IDF project using SPIFFS to store various files.
It's mostly going as expected, but I noticed some anomalies.
Reading and writing the files with fopen, fread and fwrite works fine.
While implementing a initial test to check if the file exists and write a blank file if it doesn't I realized, that the access() function always returns -1 to signal the file does not exist. I literally open it with fopen in read mode and the pointer is not NULL, still access returns an error.
Don't I have the permission to check for existence?
Here is the code in question:
- ESP_LOGI(TAG, "Testing file access for: %s", path);
- FILE* test = fopen(path, "r");
- if (test == NULL) {
- ESP_LOGI(TAG, "cant read file");
- }
- fclose(test);
- if (access(path, F_OK) == -1) {
- // The log file does not exist, so initialize it with a base structure
- FILE* file = fopen(path, "wb");
- if (file == NULL) {
- ESP_LOGE(TAG, "Failed to create file: %s", path);
- return ESP_FAIL;
- }
- else {
- ESP_LOGI(TAG, "file created: %s", path);
- }
- if (fwrite(data, size, 1, file) != 1) {
- ESP_LOGE(TAG, "Failed to write init structure to file: %s", path);
- fclose(file);
- return ESP_FAIL;
- }
- else {
- ESP_LOGI(TAG, "wrote data to file: %s", path);
- }
- fclose(file);
- }