我正在尝试创建一个函数,该函数将从存储在ESP8266上的SPIFFS中的文本文件中删除一行。我试着遵循在https://forum.arduino.cc/index.php?topic=344736.msg2380000#msg2380000中找到的“空格覆盖”方法,但是我最终得到了一行空格。
我的理解是它应该像下面这样工作,用-表示替换空间。有问题的文件只在行尾有\n。
Before
======
This is a line of text\n
This is another line of text\n
And here is anotherReplace line 2 with spaces
==========================
This is a line of text\n
----------------------------\n
And here is anotherDesired result
==============
This is a line of text\n
And here is another我实际得到的结果如下所示。
Actual result
=============
This is a line of text\n
\n
And here is another文件大小也保持不变。
下面是我正在使用的deleteLine函数。
bool deleteLine (char* path, uint32_t lineNum) {
if (!SPIFFS.begin()) {
Serial.println("SPIFFS failed!");
SPIFFS.end();
return false;
}
File file = SPIFFS.open(path, "r+");
if (!file) {
Serial.println("File open failed!");
file.close();
SPIFFS.end();
return false;
}
uint32_t size = file.size();
file.seek(0);
uint32_t currentLine = 0;
bool lineFound = false;
for (uint32_t i = 0; i < size; ++i) {
if (currentLine == lineNum) {
lineFound = true;
for (uint32_t j = i; j < size; ++j) {
uint32_t currentLocation = j;
char currentChar = (char)file.read();
if (currentChar != '\n') {
file.seek(j);
file.write(' ');
} else {
break;
}
}
break;
}
char currentChar = (char)file.read();
if (currentChar == '\n') {
++currentLine;
}
}
file.close();
SPIFFS.end();
if (lineFound) {
return true;
} else {
return false;
}
}我是不是做了什么傻事?
我知道我可以做的是创建一个新文件,复制原始文件,省略行,但是,我正在处理2x个文件,每个文件大约1MB,并且需要额外的1MB可用空间来存放临时文件,这是不理想的。
我还感兴趣的是,是否有任何方法可以截断文件。如果有,我可以遍历整个文件,替换字符,从本质上删除所需的行,然后添加一个文件结尾字符,或截断以删除文件末尾的垃圾。
发布于 2020-03-22 19:35:08
您想要做的是直接在低级写入文件系统,这是在提供的链接中完成的(因此,在具有开源硬件/软件的微控制器上,您有更多的选项,而不仅仅是文件读取和写入,就像在基于PC的操作系统中一样)。
for(uint8_t i=0;i<32;i++) ch[i]=' '; 尝试替换为
for(uint8_t i=0;i<32;i++) ch[i]='X';你会看到它起作用了(至少对我来说是这样)。我使用一个动态行长=从上一个\n到要覆盖的行的\n的字符计数。为了安全起见,我会检查文件大小。有时,我会通过将旧文件重命名为bak来压缩文件,删除所有“空”行,并在将新文件写入SPIFFS时忽略它们。对于最大64kb的大型配置文件,工作无懈可击。
https://stackoverflow.com/questions/59390844
复制相似问题