SPIFFS 更改文件中特定行的内容

问题描述

我使用 ESP32 和 SPIFFS 已经有一段时间了。我的项目将涉及在用户需要时更改文件中特定行的内容。该文件将始终以相同的格式保存,因此我知道将更改哪一行。

我当前的文件是这样存储的:

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

用户更改应用程序中的 Internet ssid 时,我的 esp32 将从数据库中读取内容并检测更改。它将存储传入的更改并更新行。

比如我把数据改成“int ssid Now”,数据库会读取并把“internet ssid”改成“int ssid Now”。我只想从那一行更新内容,但我没有找到任何内容。如果我没有通过更新找到解决方案,我将不得不从文件删除所有内容,然后创建一个新的内容来更改该行。

我像这样附加数据:

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();
}
``

解决方法

C 不支持更新文件的一部分。

您可以将旧文件的内容复制到新文件中并在将其写入新文件之前更改一行。

或者,如果您使用的是 arduino 框架,也许您可​​以查看 settings 类 (如果您使用的是 ESP IDF,则为 NVS api)