greiman/SdFat

Questions about file opening mode a+

jie326513988 opened this issue · 2 comments

When I use A+ mode to open a file, the obtained file position should be the size of the file, but now it is 0. Is my configuration wrong?

FsFile uf = sd.open(txt_indexesPath, O_RDONLY);
for (uint8_t i = 0; i < uf.size(); i++)
{
    Serial.print(char(uf.read()));
}
uf.close();
Serial.println();

uf = sd.open(txt_indexesPath, O_RDWR | O_APPEND | O_CREAT);
Serial.print("size:"); Serial.println(uf.size());
Serial.print("pos1:"); Serial.println(uf.curPosition());
uf.print("happy");
Serial.print("pos2:"); Serial.println(uf.curPosition());
uf.close();
Serial.println();

uf = sd.open(txt_indexesPath, O_RDONLY);
for (uint8_t i = 0; i < uf.size(); i++)
{
    Serial.print(char(uf.read()));
}
uf.close();

Serial port output

0000000100000741
size:16
pos1:0
pos2:21

0000000100000741happy

O_APPEND does not open the file at the end. See this

O_APPEND
If set, the file offset will be set to the end of the file prior to each write.

You may want O_AT_END which opens a file at EOF but does not position the file after the open call.

O_APPEND does a seek to EOF before every write and can be slower than O_AT_END.

I added O_AT_END since that is what the Arduino SD.h wrapper did originally. SD.h now has these definitions:

#define FILE_READ O_READ
#define FILE_WRITE (O_READ | O_WRITE | O_CREAT | O_APPEND)

Thank you