In the example below, I have two functions that write numbers to two different files on an SD card. I'm using the SdFat library.

Is there any way I can combine the two functions into one, so that I can call (for example): writeToFile(int t, FileName "filename1.txt");?

In the example below, to write a value to the "temperature.txt" file, I would like to be able to call: writeToFile(7, "temperature.txt"); In my sketch I have about a dozen functions that are writing to a dozen different files, so it would be very handy to be able to combine them into one function.

I think the main part I'm stuck on is I have no idea what the filename variable would be, or how to pass the filename to the function.

#include <SdFat.h>
SdFat sd;

void setup() {
  if (!sd.begin(chipSelect, SPI_HALF_SPEED)) {


void setTemperature(int t) {
  SdFile rdfile("temperature.txt", O_WRITE);

void setFanSpeed(int t) {
  SdFile rdfile("fanspeed.txt", O_WRITE);

String literals are of type const char *. Ordinary char *s can be passed to it though; the const means that the compiler will make sure that the function doesn't attempt to change the contents.

void setFileParameter(const char *filename, int value)
  • Thanks! It worked! I had assumed I'd be able to do the next part on my own, but ran into a smaller problem. I have another function to read the parameter from a file, so for example: readFileParameter(const char *filename, int value). I would like to call: readFileParameter("temperature.txt", currentTemp);, and have it store the value from the file into the integer currentTemp. What would I have to use instead of "int value", in order for it to change a global variable (like currentTemp)? I'm sorry that this is probably very basic stuff that I'm missing. – Jerry Aug 6 '15 at 16:59
  • I think I might've figured out my 2nd problem on my own. It seems to be working if I declare the function like this: void readFile(const char *filename, int &value). I guess the '&' causes it to modify the variable that is passed to it? It's a little too complex for my current understanding, but so far it seems to work. It would be nice if anyone points out if it's incorrect. :) – Jerry Aug 6 '15 at 18:03
  • 1
    @Jerry: That's the correct way to do it in C++. en.wikipedia.org/wiki/Reference_%28C%2B%2B%29 – Ignacio Vazquez-Abrams Aug 6 '15 at 18:05

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.