Search code examples
c++carduinoesp32spiffs

SPIFFS save return key into string


When reading a .txt file line by line with SPIFFS on my ESP32 it saves the return keys also, is there a way to prevent this?

Function for reading:

String line_one, line_two;

void readfiles() {
  char buffer[64];
  int i = 0;

  File file0 = SPIFFS.open("/0.txt", "r");
  while (file0.available()) {
   int l = file0.readBytesUntil('\n', buffer, sizeof(buffer));
   buffer[l] = 0;
   if (i == 0) {
    line_one = buffer;
   }
   if (i == 1) {
    line_two = buffer;
   }
   i++;
   if (i == 2){
    break;
   }  
  }
  file0.close();
} 

Content of my 0.txt:

2020-01-01
2021-03-16

I wanted to display them with the help of a "String processor" on a webpage:

String processor(const String& var){
  //JUST FOR EDIT
  if(var == "LINE_ONE"){
    return line_one;
  }
  else if(var == "LINE_TWO"){
    return line_two;
  }

Webpage:

<form action="/get">
  Date 1: <br><input type="date" name="1_input" id="1_input" value="%LINE_ONE%"><br><br>
  Date 2: <br><input type="date" name="2_input" id="2_input" value="%LINE_TWO%"><br><br><br>
  <input type="submit" value="Submit">
</form>

I expected, that it will set the date, but what it does is doing a return in my code after %LINE_ONE% so that the html page fails to display the date. The second line works as it is the last line that does not have a invisible return key.

Here you can see what i mean: screenshot

Thanks and greetings from germany!


Solution

  • I found out the answer by myself. It has something to do with "carriage return" (/r) and "line feed" (/n).

    Windows Notepad do a CR and then a LF at the end of a line, so i solved this error by removing the LF with notepad++ and changing a line in my code.

    From this:

    int l = file0.readBytesUntil('\n', buffer, sizeof(buffer));
    

    to this:

    int l = file0.readBytesUntil('\r', buffer, sizeof(buffer));
    

    (If i remove the CR my ESP32 crash on boot with: "Guru Meditation Error: Core 1 panic'ed (LoadProhibited). Exception was unhandled.")