How to read and write to a file from the SD card on the Yún

Hi,

I would like, as the title already tells, to know the code that you need in order to read and write to a file from the SD card on the yun. I’ve already spent many hours on trying to figure out a way on how to solve my issue but nothing that I was able to find was helpful. Anyway, if someone could help me with my problem I would be very pleased.

Thanks in advance,

NotJohn

This is what I use, adapted from what I found in a tutorial:

#include <Bridge.h>
#include <FileIO.h>

...


Bridge.begin();
FileSystem.begin();

...


writeToFile("Booted", "CPlog", 1);


...

void writeToFile(String data, String dest, int append) { //this function takes a String of data to be written, a String of desired destination file name (name only, not path or extension), and a int 1=append data 0=overwrite data.
  String destn = "/mnt/sda1/" + dest + ".txt"; //this builds the file path
  int charlen = destn.length() + 1; //this calculates the needed char length + 1 for a NULL at the end
  char destin[charlen];  //initializes the char array
  destn.toCharArray(destin, charlen); //stores the file path as a char array
  if (append == 0) FileSystem.remove(destin);  //if the option is set to overwrite the file, removes the old file
  File dataFile = FileSystem.open(destin, FILE_APPEND); //writes to the file
  if (dataFile) {  // if the file is available, write to it:
    dataFile.println(data);
    dataFile.close();
  }
}

This assumes that your SD card is loaded in as /mnt/sda1 (default at least in my experience).