0

I'm trying to create a comma delimited file using this SDFat library

Calling this code creates my file

const char Header[24]="Desired RPM,Output RPM\n";
...
foo()
{
  SpeedCache.open("/Speed_Cache.txt",O_CREAT | O_RDWR | O_APPEND);
  SpeedCache.write(Header);
  SpeedCache.sync();
}
...

After running, I have a file containing

Desired RPM,Output RPM'\n'

When I call the following function, I want it to add int target and int reference to the bottom of the file.

bool SDClass::SetLine(SdFile Cache,int target, int reference)
{   
  bool good = false;
  char NewLine[32];
  Cache.seekEnd();
  sprintf_P(NewLine,(PGM_P)F("%d,%d\n"),target,reference);
  Serial.println(good=Cache.write(NewLine));
  Cache.sync();
  return good;
}

On the first call, this works so for an input of SpeedCache,50,100 I get

Desired RPM,Output RPM'\n'

50,100'\n'

However, if I then write an input of SpeedCache,5,10 I get

Desired RPM,Output RPM'\n'

5,10'\n'

How do I adjust my function so that I will get:

Desired RPM,Output RPM'\n'

50,100'\n'

5,10'\n'

1

You just need to open the file in APPEND mode:

SpeedCache.open("/Speed_Cache.txt",O_CREAT | O_RDWR | O_APPEND);

O_APPEND

The file is opened in append mode. Before each write, the file offset is positioned at the end of the file, as if with lseek.

You should also pass your file around by reference so it doesn't keep creating new copies of the internal structure:

bool SDClass::SetLine(SdFile &Cache,int target, int reference)
  • Adding | O_APPEND had no effect – ATE-ENGE Aug 29 '17 at 14:52
  • Ok, passing the file by reference was the last thing needed for it to work. – ATE-ENGE Aug 29 '17 at 15:10
0

How do you pass the file by reference?

SdFat sd;
SdFile DataFile;

isSD = DataFile.open(FileName, O_WRITE | O_CREAT | O_AT_END);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.