however my propose wish to access by fopen() for low-level another c library.
I can test to write a file on SPIFFS by fopen() with the following code.
Code: Select all
#include "FS.h"
#include "SPIFFS.h"
void listDir(fs::FS &fs, const char * dirname, uint8_t levels=0);
void setup(){
Serial.begin(115200);
SPIFFS.begin();
FILE* f = fopen("/spiffs/hello.txt", "w");
if (f == NULL) {
Serial.println( "Failed to open file for writing");
return;
}
fprintf(f, "Hello World!\n");
fclose(f);
Serial.println("file created");
listDir(SPIFFS, "/"); // from this result, it founds "hello.txt" on SPIFFS
}
void loop(){
}
void listDir(fs::FS &fs, const char * dirname, uint8_t levels) {
Serial.printf("Listing directory: %s\r\n", dirname);
File root = fs.open(dirname);
if (!root) {
Serial.println("- failed to open directory");
return;
}
if (!root.isDirectory()) {
Serial.println(" - not a directory");
return;
}
File file = root.openNextFile();
while (file) {
if (file.isDirectory()) {
Serial.print(" DIR : ");
Serial.println(file.name());
if (levels) {
listDir(fs, file.name(), levels - 1);
}
} else {
Serial.print(" FILE: ");
Serial.print(file.name());
Serial.print("\tSIZE: ");
Serial.println(file.size());
}
file = root.openNextFile();
}
}
however when I want to test reading the "hello.h" file. It can't read.
Code: Select all
// TEST for reading by fopen() on SPIFFS
#include "FS.h"
#include "SPIFFS.h"
void listDir(fs::FS &fs, const char * dirname, uint8_t levels=0);
void setup(){
Serial.begin(115200);
SPIFFS.begin();
listDir(SPIFFS, "/"); // from this result, it founds "hello.txt" on SPIFFS
FILE* f = fopen("/spiffs/foo.txt", "r");
if (f == NULL) {
Serial.println("Failed to open file for reading");
return;
}
char line[64];
fgets(line, sizeof(line), f);
fclose(f);
Serial.println(line);
}
void loop(){
}
void listDir(fs::FS &fs, const char * dirname, uint8_t levels) {
Serial.printf("Listing directory: %s\r\n", dirname);
File root = fs.open(dirname);
if (!root) {
Serial.println("- failed to open directory");
return;
}
if (!root.isDirectory()) {
Serial.println(" - not a directory");
return;
}
File file = root.openNextFile();
while (file) {
if (file.isDirectory()) {
Serial.print(" DIR : ");
Serial.println(file.name());
if (levels) {
listDir(fs, file.name(), levels - 1);
}
} else {
Serial.print(" FILE: ");
Serial.print(file.name());
Serial.print("\tSIZE: ");
Serial.println(file.size());
}
file = root.openNextFile();
}
}
Thank you.