2

我正在尝试创建一个函数,该函数将从 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 可用空间,这并不理想.

我也对是否有任何方法可以截断文件感兴趣。如果有,我可以遍历文件,替换字符以基本上删除所需的行,然后添加文件结尾字符,或截断以消除文件末尾的垃圾。

4

1 回答 1

0

您想要做的是直接在提供的链接中完成的文件系统的低级别写入(因此,在具有开源硬件/软件的微控制器上,您有更多的选择,而不仅仅是基于 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 的大型配置文件。

于 2020-03-22T11:35:07.807 回答