Your new topic does not fit any of the above??? Check first. Then post here. Thanks.

Moderator: igrr

User avatar
By Ghassan Yusuf
#70845 Dear Friends

Good day to you, i am building a custom application that requires storing data in SPIFFS in string format, not json. because i am using a GPS module and storing a string into the file. the problem is i dont know how to read from the file.

the code is printing data in the file from serial port, and when i restart the esp it should pring the information in the file

could any one help me ?!

here is the code

Code: Select all#include <FS.h>
const String FileName = "GPS_TEST.txt";

bool readFile(String FileName) {
  File myFile = SPIFFS.open(FileName, "r");
  if (!myFile) {
    Serial.println("-> Couldn't Load The File");
    return false;
  } else {
    Serial.println(myFile);
    return true;
  }
}

bool writeFile(String FileName, String Message) {
  if(checkFile(FileName)) {
    File myFile = SPIFFS.open(FileName, "w");
    if(myFile) {
      myFile.println(Message);
      myFile.close();
      return true;
    }
  } else {
    return false;
  }
}

bool checkFile(String FileName) {
  if(SPIFFS.exists(FileName)) {
    return true;
  } else {
    return false;
  }
}

bool createFile(String FileName) {

  File myFile = SPIFFS.open(FileName, "w");
 
  if(myFile) {
    myFile.close();
    return true;
  } else {
    return false;
  }
}

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  Serial.println("");
  Serial.println("");
  SPIFFS.begin();

  if(!checkFile(FileName)) {
    Serial.println("The File Doesnt Exist !!!");
    Serial.println("-> Creating File " + FileName);
    if(createFile(FileName)) {
      Serial.println("-> " + FileName + ", Created Successfully");
    } else {
      Serial.println("-> Couldn't Create " + FileName + " File");
    }
  } else {
    Serial.println("The File : " + FileName + " Exist");
    Serial.println("Reading " + FileName + " Content : ");
    readFile(FileName);
  }
}

void loop() {
  if(Serial.available()) {
    String Message = Serial.readString();
    Message.trim();
    if(writeFile(FileName, Message)) {
      Serial.println("-> Successfully Printed A Message In " + FileName);
      Serial.println("-> Message : " + Message + ".");
    } else {
      Serial.println("-> Failed To Print Message In File");
    }
  }
}


waiting for your help guys
User avatar
By martinayotte
#70846 Your readFile() function is not doing any read() from the file, it is only printing the file handle.
You need to do a while loop with a myFile.read(&ch, 1), where ch is a char, and print one character at a time, for example.