zidarm
zidarm

Reputation: 25

ESP8266 SPIFFS copy content of file, delete & rename

I have a problem where I copy everything but the first line from file to another temporary file. Then I delete the original file and rename the temporary one to original. After every cycle I also append a line of data to the original file. The code works fine for the first time it runs, then content disappears and only 1 line is in the original file.

Original file:

line 1: aaa
line 2: bbb
line 3: ccc
line 4: ddd
line 5: eee

After I run the function for the first time:

First cycle:

line 1: bbb
line 2: ccc
line 3: ddd
line 4: eee
line 5: fff

After second cycle:

line 1: ggg

Update:

Looks like that when I rename the file and open it with spiffs, esp doesn't see the content of the file so it just writes the line that gets added after the function ends.

Update2:

Even if I comment out my function that adds lines to the file, the deleteFirstLine function doesn't work. I tried using the function on a file with 5 lines in it. Same result, first cycle is okay, then the second one nothing is in the file...

Code that I use in Arduino:

void deleteFirstLine(String filename){
    File original = SPIFFS.open(filename, "r");
    String name_ = original.name();
    Serial.println(name_);
    if (!original) {
      Serial.print("- failed to open file "); Serial.println(filename);
    }else{
      Serial.print("- DELETING FROM FILE "); Serial.println(filename);
      //We skip the first line
     original.readStringUntil('\n');
     File temporary = SPIFFS.open(TEMP_PATH, "w+");
     if(!temporary){
      Serial.println("-- failed to open temporary file "); 
     }else{
      while(original.available()){
        temporary.print(original.readStringUntil('\n')+"\n");
      }
      temporary.close(); 
     }
     original.close();    
     
     if(DEBUG == 1){   
         if(SPIFFS.remove(filename)){
            Serial.println("Old file succesfully deleted");
         }else{
            Serial.println("Couldn't delete file");
         }
         if(SPIFFS.rename(TEMP_PATH,filename)){
            Serial.println("Succesfully renamed");
         }else{
            Serial.println("Couldn't rename file");
         } 
      }else{
        SPIFFS.remove(filename);
        SPIFFS.rename(TEMP_PATH,filename);
      }
    } 
}

Upvotes: 0

Views: 5999

Answers (1)

zidarm
zidarm

Reputation: 25

Alright, got the thing working. The problem was i didn't add "\n" when i printed into the file. so that way I just printed a long line of data into the file which I skip with the function. Fixed the code so it works now.

Upvotes: 0

Related Questions