Arduino IDE ESP32 device using SPIFFS to save

  arduino-ide, c++, esp32, spiffs

I writing ESP32 program and using SPIFFS to save some data because I do not want to loose it after I power down the device.

I have 2 functions:

char* readFile(fs::FS &fs, const char *path)
{
    Serial.printf("Reading file: %sn", path);

    File file = fs.open(path);
    if (!file || file.isDirectory())
    {
        Serial.println("Failed to open file for reading");
        return "FAIL";
    }

    Serial.print("Read from file: ");
    while (file.available())
    {
        Serial.write(file.read());
        delayMicroseconds(100);
        //TODO
        //append all characters and return it as a list of char arrays at the end of reading
    }
    file.close();
    
}


void writeFile(fs::FS &fs, const char *path, const char *message)
{
    Serial.printf("Writing file: %sn", path);

    File file = fs.open(path, FILE_WRITE);
    if (!file)
    {
        Serial.println("Failed to open file for writing");
        return;
    }
    if (file.print(message))
    {
        Serial.println("File written");
    }
    else
    {
        Serial.println("Write failed");
    }

    file.close();
}

First of all, I run my program and call writeFile() and then followed by readFile():

    int n = 0;
    Wifi_setup();
    Spiffs_setup();
    n = scan_wifi_networks();

    
    Serial.print("list_strings outside scan function = ");
    for (int i = 0 ; i<=n ; i++){
      Serial.println(found_networks[i]);
    }
    //compare list_strings with preset wifi networks. If match, everything is fine, if not, problem!


    writeFile(SPIFFS, "/wifi.txt", "Telia-33F8A3-Greitas");
    char* known_networks = readFile(SPIFFS, "/wifi.txt");

 
    //send USD to the server, go back to sleep
    //initialize_deep_sleep();
}

And that part works fine. From the serial monitor, I can see that it have sucesfully written my text to wifi.txt.

After I run write/read functions

Next, I comment out write function and only leave read function.I run the code again and it is not able to read back my text:

Only readFile

Can someone help me understand why is that happening? I thought that if I write to spiffs once, I will be able to access it afterwards but that is not the case. I have previously used EEPROM and that seemed to work. I can write to EEPROM address and simply access the same address later and the value will still be there after the power off. Any help is appreciated. Thanks in advance.

Source: Windows Questions C++

LEAVE A COMMENT