首页 > 解决方案 > 将文件读入 char 数组,避免使用 Arduino 的字符串

问题描述

我有一个 config.json 文件存储在基于 ESP8266 的 Web 服务器的 Flash SPIFFS 内存中。

我的意图是将此文件读入一个字符数组(char string[]),避免使用 Arduino 的字符串,并在 Ajax 调用后将其发送给客户端。

config.json 是这样的: {"start1h":11,"start1m":20,"stop1h":15,"stop1m":40}

我已经尝试使用以下代码,但问题是客户端收到一个末尾带有“@”字符的字符串,并且无法通过 javascript 解析该字符串

#define CONFIGFILE "/config.json"
File configFile = SPIFFS.open(CONFIGFILE, "r");

 size_t filesize = configFile.size(); //the size of the file in bytes     
 char string[filesize + 1];   // + 1 for '\0' char at the end      

 configFile.read((uint8_t *)string, sizeof(string));  
 configFile.close(); 
 string[filesize+1] = '\0';
 Serial.print(string);    

 server.send(200, "text/plane", string);

串口输出:{"start1h":11,"start1m":20,"stop1h":15,"stop1m":40}@

客户端收到 ajax 响应:{"start1h":11,"start1m":20,"stop1h":15,"stop1m":40}@

@ 在字符串的末尾!

我的代码有什么问题?提前致谢

标签: arraysjsonstringarduino-esp8266spiffs

解决方案


我意识到这个问题是几个月前的问题 - 我在寻求帮助以使类似系统正常工作时遇到了你的问题,我想我在你的代码中发现了错误。

您将 \0 nul 字符放在数组末尾之外。

如果数组有 filesize+1 个元素,则需要插入 nul 字符的最后一个元素是 string[filesize],而不是 string[filesize+1]。


推荐阅读