替换 esp32 上 sd 卡文本 (gpx) 文件的最后一行

问题描述 投票:0回答:1

我正在尝试将 gpx 轨迹从 GPS 写入 ESP32 上的 SD 卡。由于我不太熟悉 c,所以我很难完成这项任务:

每次我向文件写入新的轨道段时,我想首先删除结束行,如下所示:

  if (gpsFixExists && dateIsValid && timeIsValid)
  {
    if (state.currentGPXFile == "")
    {
      String filename = "/" + String(state.dateYear) + String(state.dateMonth) + String(state.dateDay) + "_" + String(state.timeHours) + String(state.timeMinutes) + String(state.timeSeconds) + ".gpx";
      state.currentGPXFile = filename.c_str();
      File gpxFile = SD.open(state.currentGPXFile.c_str(), FILE_WRITE);
      // Write GPX header and metadata
      gpxFile.println("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\" ?>");
      gpxFile.println("<gpx version=\"1.1\" creator=\"Open Rally Computer - https://github.com/pcace/open-rally-computer\">");
      gpxFile.println("<metadata>");
      gpxFile.println("<name>" + filename + "</name>");
      gpxFile.println("<desc>Track log generated by Open Rally Computer</desc>");
      gpxFile.println("</metadata>");
      gpxFile.println("<trk><name>Track Log</name><trkseg>");
      gpxFile.close();
    }

    // Open the file to append data
    File gpxFile = SD.open(state.currentGPXFile.c_str(), FILE_WRITE);
    if (gpxFile)
    {
      // Move to the end of the file, then seek back to overwrite the closing tags
      long position = gpxFile.size() - strlen("</trkseg></trk></gpx>") - 1; // Adjusted to account for newline characters
      gpxFile.seek(position);
      // Write the new track point
      gpxFile.println("<trkpt lat=\"" + String(state.currentLatitude, 6) + "\" lon=\"" + String(state.currentLongitude, 6) + "\">");
      gpxFile.println("<ele>" + String(state.currentAltitude, 2) + "</ele>");
      gpxFile.println("<time>" + String(state.dateYear) + "-" + String(state.dateMonth) + "-" + String(state.dateDay) + "T" + String(state.timeHours) + ":" + String(state.timeMinutes) + ":" + String(state.timeSeconds) + "Z</time>");
      gpxFile.println("</trkpt>");
      // Re-append the closing tags
      gpxFile.println("</trkseg></trk></gpx>");
      gpxFile.close();
    }
  }

这两行不正确:

      long position = gpxFile.size() - strlen("</trkseg></trk></gpx>") - 1; // Adjusted to account for newline characters
      gpxFile.seek(position);

如何正确地将关闭线替换为新的轨道段?

非常感谢!

c++ arduino esp32 gpx
1个回答
0
投票

您可以通过在写入文件的结束(短暂)部分之前拾取文件中的位置来完成此操作。然后当你进行下一次写入时,使用seek()将其设置为你保存的位置。

我已经在 ESP32 上进行了测试,代码如下,效果很好。

String filename = "/text.txt";
File f = SD.open(filename, FILE_WRITE);
if (f) {
    f.println("Data to keep");                       
    int intPosition = f.position();
    f.println("ephemeral_1");

    delay(2000);
    
    f.seek(intPosition);
    f.println("More data to keep");                       
    intPosition = f.position();
    f.println("ephemeral_2");
    f.close();                                             
}  

当你读完最后的代码时,它会给出:

Data to keep
More data to keep
ephemeral_2

缺少 ephemeral_1。

© www.soinside.com 2019 - 2024. All rights reserved.