Hi guys! I've got a file.txt which contains 30 lines. I need to iterate over the lines and divide the file in three smaller packages each with 10 lines. I was trying with this function but I know it's not correct, anyone could help me? Thanks a lot
void readHistory(){
File file = LittleFS.open("/file.txt", "r");
if(!file){
Serial.println("File open failed");
} Serial.println("------ Reading ------");
int i = 0;
int samples = 10;
while (i<=samples && i!=30){
String myString;
myString.substring(i,samples); // <--- I know this is not correct but I was looking for something like this
Serial.print("Package: ");
Serial.println(myString);
i = samples;
samples = samples + i;
}
file.close();
}//end readHistory
1/ open your main file, if it fails, don't try to proceed.
2/ then you need to open the first output file for writing and set a count variable to 0 (check of course opening the file did work, if not stop)
3/ read a byte from the main
4/ if there is no more byte to read, then close the file, you are done.
5/ if you read a byte, write it to the output file
6/ if the byte == '\n' then increment the count variable.
7/ if count is 10 then you are done reading 10 lines. Close the output file and open the next one for writing and reset the count variable to 0
8/ go back to step 3
the DumpFile example will show you how to read data from a file. instead of writing to the serial monitor, just write to the output file.
Ok, but if I read the first 10 lines and save them in the first output file, when I open the next output file how can I start reading my main file from the 10th line?
Could you provide a little bit of code?
this line of code const byte outputCount = sizeof outputFileNames / sizeof outputFileNames[0];
calculates the number of file names in my outputFileNames array. this way I don't have to hardcode 3
The variable byte outputIndex = 0; was meant to be an index to keep track of how many files had been written (to see if the for loop went all the way or exited early) but I forgot to add that
add this line just before we close the destination file
outputIndex = idx; // <<---- keep track of how many files got written
destinationFile.close();
this way at the end of the function you can return a bool if all the files were split for example
Cool that works! Last question, I implemented these lines of code in a function that everytime I read an output file the program send the values through an HTTP request. Every value of out1.txt and out2.txt is send correctly, but I receive just seven values of the third output file. What could be the problem? Thanks a lot