I'm codding for Arduino (ESP8266), and have to read a string from a file, to use it. I don't know how long is that file, so I have to create a char*
and pass it to the readConf
function so that malloc
decides for the memory size.
void readConf(char path[], char **buff){
SPIFFS.begin();
if (SPIFFS.exists(path))
{
File file = SPIFFS.open(path, "r");
int size = file.size();
Serial.print("File size: ");
Serial.println(size);
char *bu;
bu = (char*) malloc((size+1) * sizeof(char));
file.read((uint8_t*) bu, size);
bu[size] = '\0';
Serial.print("Data: ");
for (int i = 0; i < size; i++)
Serial.print(bu[i]);
Serial.println("");
//Everything is OK. It is printed correctly.
buff = &bu; //!This is the problem!
file.close();
}
SPIFFS.end();
}
#define file_path "/file"
void setup(){
if(WiFi.getMode() != WIFI_STA)
WiFi.mode(WIFI_STA);
char* username;
readConf(file_path, &username);
char* password;
readConf(file_path, &password);
/*The same with password. */
WiFi.begin(username, password);
Serial.print("username: ");
Serial.println(username); //Here I sometimes get Exception, and sometimes prints non-sense characters
free(username); //My memory is limited. I'm doing all this stuff for this line!
//...
}
I also searched a lot in StackOverflow and other sites, also used char *
, char **
, filling the pointer directly in the readConf
function, and a lot more but non of them worked. How should I deal with it? Can I do it at all?
NOTE: I should not use String class.