Split a file.txt in multiple packages

maybe something like this (typed here, so totally untested)

void readMain() {
  const char * outputFileNames[] = {"/out1.txt", "/out2.txt", "/out3.txt"};
  const byte outputCount = sizeof outputFileNames / sizeof outputFileNames[0];
  byte outputIndex = 0;

  File sourceFile;
  File destinationFile;
  String aLine;
  aLine.reserve(20);

  sourceFile = LittleFS.open("/file.txt", "r");
  if (!sourceFile) {
    Serial.println(F("Error: file.txt open failed"));
  } else {
    for (byte idx = 0; idx < outputCount; idx++) {
      if (sourceFile.available() == 0) break;
      destinationFile = LittleFS.open(outputFileNames[idx], "w");
      if (!destinationFile) {
        Serial.print(F("can't open destination "));
        Serial.println(outputFileNames[idx]);
        break;
      } else {
        int lineCount = 0;
        while (sourceFile.available() && (lineCount < 10)) {
          aLine = sourceFile.readStringUntil('\n');
          destinationFile.println(aLine); // double check if the '\n' is in the String or not (--> print or println accordingly)
          lineCount++;
        }
        destinationFile.close();
      }
    } // end for
    sourceFile.close();
  }
}
1 Like