Search code examples
arduinocharintspiffs

Arduino converting value from file.read() to const char*


I know that there is a lot of subject regarding the variable conversion but I spend more than 2 hours on different forum and I don't find how to solve my problem ...

I've got a code which is going to read on SPIFFS file on my ESP32 and write it into the Serial monitor. (Here we are on the sample code given on many website)

But now how can I send the value of file.read() into a const char* I really need this format because of the function which will receive the value ...

My code :

const char* VALUE     = "";

File file = SPIFFS.open("/test.txt");
      if(!file){
          Serial.println("Failed to open file for reading");
          return;
      }

      while(file.available()){
        Serial.write(file.read());
        VALUE = file.read();
      }
      file.close();

This result as : invalid conversion from int to const char*


Solution

  • Try the following:

    char VALUE [512] = {'\0'};  // 511 chars and the end terminator if needed make larger/smaller
    
    File file = SPIFFS.open("/test.txt");
      if(!file){
          Serial.println("Failed to open file for reading");
          return;
      }
      uint16_t i = 0;
      while(file.available()){
         VALUE [i] = file.read();
         // Serial.print (VALUE [i]); //use for debug
         i++;
      }
      VALUE [i] ='\0';
      // Serial.print (VALUE); //use for debug
      file.close();
    

    This copies the content of the file into a char array, which can then be used for further processing. If the char array is defined globally it is compiled to flash and prevents memory fragmentation