SPIFFS How to copy and paste a file in time of execution?
Posted:
Tue Dec 01, 2020 2:31 am
by FRANCISCOGIMENO1000
Hello friends, I am with an esp8266 and I have a question, I have searched but I cannot find a function for SPIFFS to be able to make a copy of an existing file type:
Copyfunction (original_file_name, copy_file_name);
Do you know if there is something or I have to create a function to do it?
Greetings and thank you
Francisco
Re: SPIFFS How to copy and paste a file in time of execution
Posted:
Tue Dec 01, 2020 9:55 am
by btidey
Note SPIFFS is deprecated in favour of LittleFS now. API is pretty identical.
There is no inbuilt copy file function so you need to supply your own.
It is pretty straightfoward. E.g.
Open source file for reading giving input stream
Open destination file for writing (creates it) giving output stream
readBytes from input stream into a buffer
writeBytes to output stream from that buffer
repeat until file size is done.
close both files
You can choose buffer size to suit your purposes of speed / memory usage.
Termination of read/write cycle can be done either by checking size up front or by using the count coming back from readbytes. E.g. if it is less than size requested then it is the last block.
Re: SPIFFS How to copy and paste a file in time of execution
Posted:
Wed Dec 02, 2020 3:27 am
by FRANCISCOGIMENO1000
In case someone is worth it, here you have the function.
Code: Select all
void CopiaPega(String FileOriginal, String FileCopia)
{
char ibuffer[64]; //declare a buffer
Serial.println("In copy"); //debug
if (LittleFS.exists(FileCopia) == true) //remove file copy
{
LittleFS.remove(FileCopia);
}
File f1 = LittleFS.open(FileOriginal, "r"); //open source file to read
if (!f1)
{
Serial.println("error 1"); //debug
}
File f2 = LittleFS.open(FileCopia, "w"); //open destination file to write
if (!f2)
{
Serial.println("errror 2"); //debug
}
while (f1.available() > 0)
{
byte i = f1.readBytes(ibuffer, 64); // i = number of bytes placed in buffer from file f1
f2.write(ibuffer, i); // write i bytes from buffer to file f2
}
f2.close(); // done, close the destination file
f1.close(); // done, close the source file
Serial.println("End copy"); //debug
}