Problem using to append data at the start of a file

I encounter some problem using with SD library (try both 1.2.0 and 1.2.3)

My idea is to append some data from sensor at the begining of my sd file (instead of at the end as usually) to allow easier reading after (just have to count for 10 first lines from start that will represent the more recent data point).

I record data1, then data2 then data 3 and I want the file to be as follow :

I can’t get it to work.
I will have :

of if I delete O_APPEND, I get just

Any advice ?
Thank you

I made a small exemple based on the build-in tutorial SD/Datalogger :
#include <SPI.h>
#include <SD.h>

const int chipSelect = 4;

void setup() {
// Open serial communications and wait for port to open:
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only

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.”);

void loop() {
// make a string for assembling the data to log:
String dataString = “”;

// open the file. note that only one file can be open at a time,
// so you have to close this one before opening another.
File dataFile =“datalog.txt”, O_READ | O_WRITE | O_CREAT | O_APPEND);

// if the file is available, write to it:
if (dataFile) {
for(int i=1;i<=3;i++){;
// print to the serial port too:

// if the file isn’t open, pop up an error:
else {
Serial.println(“error opening datalog.txt”);

I think the word you want is "insert" data, not "append", which is at the end by definition.

No, you can only do that by copying the old data AFTER then new data.


Ok now I understand that my old data will not magically move if I insert data at the beginning. Too bad.
Thank you Paul for your help

I will have to change my reading code to read from the end of the file

I met the same problem, and I lost 3 days finding solution.

[HD: Arduino Uno R3 clone microUSB + DataLogger RTC + SD shield Uno R3].

When the file is opened with (given in arduino turtorial) FILE_WRITE, the .seek() command although rewinds the file and you can read data form the file starting from selected point, but write is always from the end of the file.

The solution is to open file with changed flags:


and then you can write in selected by .seek() command point (which gives the overwrite funcionality) , but unfortunately you need also controll file position coursor mannually. Eg. you need to rewind the file coursor to 0 before .available() comman, but eg. .read() command moves coursor one byte forward.

It is not too big deal (eg. if you read whole the file it is enough to call .seek(.size()) but must be remembered. Hope it helped.

BTW. Where is should be noticed about this error or inconvinience at least ? (is is the SD library problem as I suppouse, but I'm not sure).