arrays - 将文件读入 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}@
@ 在字符串的末尾!
我的代码有什么问题?提前致谢
解决方案
我意识到这个问题是几个月前的问题 - 我在寻求帮助以使类似系统正常工作时遇到了你的问题,我想我在你的代码中发现了错误。
您将 \0 nul 字符放在数组末尾之外。
如果数组有 filesize+1 个元素,则需要插入 nul 字符的最后一个元素是 string[filesize],而不是 string[filesize+1]。
推荐阅读
- angular - OpenLayers 6.4.3 地图更新后不显示
- javascript - 剥离某些 html 标签并返回字符串的其余部分和所有其他标签
- javascript - 我如何将密钥添加到对象本身?
- python - 如何将具有非法名称的关键字参数传递给接受 **kwargs 的函数
- bash - 在 bash 字符串变量中展开花括号和通配符(没有 eval)
- mongodb - MongoDB查找匹配坐标比较的文档
- python - 如何将三个列表转换为一个字典?
- c# - C# GraphX 在点击时高亮显示顶点
- flutter - NoSuchMethodError:在 null 上调用了“评级”
- pre-commit.com - pre-commit-config.yaml 中的 args 是否会覆盖 pre-commit-hooks.yaml 中的 args?