How to Rewind the data in a SD file?

I can't find the function in SD.h to rewind the datalog from 1st-100th to 100th-1st.
I write some function to solve it.

First, I check how many lines in the data which I want to rewind, by counting '\n'.
Second, I use readStringUntil('\n') 100 times to store the 100th String in another file
and use the for loop the decline the times from 100 to 1.

it works when I rewind less than 12 lines,but it keeps showing "error opening reverse data" when I read 100 lines...


#include <SPI.h>
#include <SD.h>

const int chipSelect = 4;

void setup() {
Serial.begin(9600);
while (!Serial) {
;
}

Serial.print("Initializing SD card...");

// see if the card is present and can be initialized:
if (!SD.begin(chipSelect)) {
Serial.println("Card failed, or not present");
// don't do anything more:
while (1);
}
Serial.println("card initialized.");

SD.remove("trackA.txt");

for (int i = 0; i < 100; i++) {
String dataString = "";
dataString = String(i+1);
File dataFile = SD.open("trackA.txt", FILE_WRITE);
if (dataFile) {
dataFile.println(dataString);
dataFile.close();
Serial.println(dataString);
}
else {
Serial.println("error opening datalog.txt");
}
}

int c;
c = Lines("trackA.txt");
Serial.println(c);

ReverseData("trackA.txt");

}

void loop(){

}

String readLine(String filename, int line){
String received = "";
File file = SD.open(filename);
if(file){
for(int i=0; i < line ; i++){
received = file.readStringUntil('\n');
}
return String(received);
file.close();
}
}

int Lines(String filename){
if (!(SD.exists(filename))) {
Serial.println("example.txt doesn't exist.");
}
int line = 0;
char ch;
File file = SD.open(filename);
if(file){
while(file.available()){
ch = file.read();
if(ch == '\n'){
line++;
}
}
}
file.close();
return line;
}

void ReverseData(String filename){
int c = Lines(filename);
String data_R = "R";
data_R += filename;
SD.remove(data_R);
for(int i = c; i >0 ; i--){
String dataString = "";

dataString = readLine(filename, i);

File dataFile = SD.open(data_R, FILE_WRITE);
if (dataFile) {
dataFile.print(dataString);
dataFile.close();
Serial.println(dataString);
}
else {
Serial.println("error opening reverse data");
}
}

}


here is the code does any one could help me to find the problem?
or there is a better way to Rewind the data in a file ?

Every time you open an SD File or use a variable from the String class, you are allocating memory and Arduinos do not have garbage collection to recycle that used memory. I'm guessing your are running out. I would suggest looking at some of the SD examples and learn how to use C strings (arrays of char with a terminating '\0') rather than Strings.

Please edit your post to add code tags, as described in How to use this forum.

To "rewind" a data file on an SD card, simply close the file and reopen it.

The OP wants to "reverse" the line order of a file into another file. Not really a "rewind" operation