SPIFFS change content from specific line in File

1.5k Views Asked by At

I have been working with ESP32 and SPIFFS for a while now. My project will involve changing the content from a specific line in the file when the user need to. The file will always be saved the same format so I know which line will be changed.

My current file is stored like this:

Content inside file: 
DeviceNmae
[email protected]
123456
button to read
uid from databa
internet ssid
internet pass

When the user changes the internet ssid in the Application, My esp32 will be reading the contento from the database and will detect the change. It will store the incoming change and update the line.

For example, I changed the data to "int ssid now", the database will read and change the "internet ssid" to "int ssid now". I would like to update the content from only that line, but I didn't find nothing on that. If I don't find the solution by updating, I will have to delete all the content from the file and create a new one only to change that line.

I append the data like this:

void funcClass::append_data(String funcName, char Text[]) {

  file = SPIFFS.open("/esp_name.txt", FILE_APPEND);

  while (connection_state == 1 and funcName == ""){
    if (connection_state == 1 and funcName == "" and stop_loop == 0){
      for (int i = 0; i < strlen(Text); i++){
        char c = Text[i];
        SerialBT.write(c);
      }  
      SerialBT.write('\n');  
    }
    stop_loop = 1;
    if (SerialBT.available()){
      while (SerialBT.available()) {
        insert_chars = SerialBT.read();
        funcName = String(funcName + insert_chars);
      }
      stop_loop = 0;
    }  
  }

  if (file.print(funcName)){
    Serial.print("data was added: ");
    Serial.println(funcName);
  }else{
    Serial.println("data was not added");
    return;
  }

  file.close();
}
``
1

There are 1 best solutions below

0
On

C doesn't support updating parts of a file.

You could either copy the content of your old file into a new one and change the one line before you write it to the new file.

Or maybe you have a look at the settings class if you are using the arduino framework (or the NVS api if you are using the ESP IDF)