我正在尝试创建一个函数,该函数将从 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 another
Replace line 2 with spaces
==========================
This is a line of text\n
----------------------------\n
And here is another
Desired 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 可用空间,这并不理想.
我也对是否有任何方法可以截断文件感兴趣。如果有,我可以遍历文件,替换字符以基本上删除所需的行,然后添加文件结尾字符,或截断以消除文件末尾的垃圾。