我正在编写 Arduino (ESP8266),并且必须从文件中读取一个字符串才能使用它。我不知道那个文件有多长,所以我必须创建一个char*
并将它传递给readConf
函数,以便malloc
决定内存大小。
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!
//...
}
我也在 StackOverflow 和其他网站上搜索了很多,也使用了char *
, char **
,直接在readConf
函数中填充指针,还有很多但都不起作用。我该如何处理?我能做到吗?
注意:我不应该使用 String 类。
函数参数buff
是函数的局部变量
void readConf(char path[], char **buff){
所以在函数内改变它
buff = &bu; //!This is the problem!
password
对函数中声明的变量没有影响setup
char* password;
readConf(file_path, &password);
你需要写
*buff = bu;
那就是您需要在函数readConf
中更改函数中password
声明的指针的值setup
所以你readConf
通过一个指向它的指针通过引用传递了指向该函数的指针
readConf(file_path, &password);
现在要直接访问原始指针,password
您需要取消引用buff
由表达式初始化的参数&password
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句