Skip to content

Question: Can I open two files from SPIFFS at same time? #4140

Closed
@drschlaumeier

Description

@drschlaumeier

Hallo,
I'm trying to optimize my code since I need to save RAM/Stack. See #4115
I came to the idea that I could move some stuff to SPIFFS. I want to read a file line by line and at the same time save some of that lines modified into another/new file on SPIFFS. So I have two files open, one for reading and one for writing.

However, If I try to open the second file for writing the ESP crashes.
Exception 3: LoadStoreError: Processor internal physical address or data error during load or store

Is it NOT allowed to have two files open the same time? So I need to search somewhere else why my code crashes?

Thanx in advance DRS

Here some code:

const char REPLACEFILE[] PROGMEM = "/somefilename.txt"; 
bool ReplaceStringInFile(const String& fname, const String& sreplace, const String& sdata){
    Serial.print(F("--> Entering ReplaceStringInFile: ")); Serial.println(fname);
    
    //open original file 
    File forg = SPIFFS.open(fname, "r");
    if (!forg) {
      Serial.print(F("  --> Error: Open File for read - ")); Serial.println(fname);
      return false;
    } 
    //open new temp file
    Serial.print(F("  --> Create tmp File: ")); Serial.println(REPLACEFILE);
    File fnew = SPIFFS.open(REPLACEFILE, "w"); //<--- CRASH IS HERE !!!!
    if (!fnew) {
      Serial.print(F("  --> Error: Open File for write - ")); Serial.println(REPLACEFILE);
      forg.close();
      return false;
    }
    
    //read line by line
    Serial.println(F("  --> Loop through file: "));
    String line;
    int i = 0;
    while(forg.available()) {
      Serial.print(String(i++));Serial.print(F(", ")); //print some line # for debugging
      line = forg.readStringUntil('\n');
      if(line.indexOf(sreplace) > 0){ //we could save this if and only call replace
        Serial.println(F("  --> Found replace string... "));
        line.replace(sreplace, sdata);      
      }
      fnew.print(line);
    }
    Serial.println("");
    forg.close();
    fnew.flush();
    fnew.close();
    
    //delete forg & rename fnew to forg
    SPIFFS.remove(fname);
    SPIFFS.rename(REPLACEFILE, fname);
    return true;
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    waiting for feedbackWaiting on additional info. If it's not received, the issue may be closed.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions