I’m using an ESP32 and the File System LittleFS to make a file. Sometimes, like in the title, I need to replace a single line in the file but i don’t want to copy the entire file. Is it possible? How can I do it?
To make problem easier, all lines can be of the same length. Also the new line.
I have tried with this code:
#include<LittleFS.h>
String stringToSearchInLine="Line 2";
String newSubString="123";
void replacePDU(const String &searchString, const String &PDU_Name) {
File file = LittleFS.open("/ReplaceLineTest.txt", FILE_WRITE);
if (!file) {
Serial.println("File open error!!");
return;
}
while (file.available()) {
// Read current position
int position = file.position();
// read a line
String line = file.readStringUntil('n');
// search something in the lines to select the one to replace
if (line.indexOf(searchString) != -1) {
int pduIndex = line.indexOf("---");
if (pduIndex != -1) {
line.replace("---", PDU_Name); //new_Name has length = 3;
// return to the position of the line to be replaced
file.seek(position);
file.print(line);
file.print("n");
break;
}else{
Serial.println("PDU Name is already assigned");
}
}
}
}
void setup(){
Serial.begin(115200);
if (!LittleFS.begin()) {
Serial.println("Error Initializing the file system");
}else{
Serial.println("File System ready");
}
File file = LittleFS.open("/ReplaceLineTest.txt", FILE_WRITE);
if (!file) {
Serial.println("Open File to write error.");
return;
}else{
file.println("Line 1 ---");
file.println("Line 2 ---");
file.println("Line 3 ---");
file.println("Line 4 ---");
file.close();
}
//Read and Stamp original file
file = LittleFS.open("/ReplaceLineTest.txt");
Serial.println(" Read from file:");
while(file.available()){
Serial.write(file.read());
}
file.close();
replacePDU(stringToSearchInLine, newSubString);
//Read and Stamp modified file
file = LittleFS.open("/ReplaceLineTest.txt");
if(!file){
Serial.println("Problem occurred during opening file");
}else{
Serial.println(" Read from file:");
while(file.available()){
Serial.write(file.read());
}
file.close();
}
}
void loop(){
}
The result was always a blank file.
New contributor
Antonio Pandalone is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.