Continue to write on a file but do not rewrite the title in every loop

Hi,

In my loop() function, I create a file X. I then write a title line in the file. I then want to write in a new line everytime a variable Y increments. Of course, I do not want to rewrite the title in the file. I cannot do the title writing in the setup loop because many X files are created during the sketch, depending on inputs (physical buttons). I guess that I therefore need to call a function which checks if something has already been written in the file, in which case the title should not be written (again) on the file. Anyone knows how I could find my way around this? (Didn’t find the function I described in the SD library)

thanks!

EDIT: I just thought of this solution:

if (! SD.exists(completefilename)) {                
           logfile = SD.open(completefilename, FILE_WRITE); 
           Serial.println("CSV File created.");
           logfile.println("Title text");
            }
logfile = SD.open(completefilename, FILE_WRITE);

This should actually do the job, right?

They surefire way not to write the title is to not write the title. The next thing to consider is if you ever need a a title. What do you do with it? I submit the only thing you need is a filename and that is something you may only need to write once but you could do that mopre frequently, like change of date, but that wouyld be the result of a condition in the loop, and not something you create every time round.

Just try it :wink:

I guess it has a bug; you open a file twice without closing it. Close it after writing the title.

Or before opening to write the data, test the logfile variable for NULL and don't open again if it is not(I don't have experience with arduino in combination with SD but it would be a usual approach in C if I recall correctly).

How about looking at the size of the file to determine if you need to write the title line?

  logfile = SD.open(completefilename, FILE_WRITE);

  // if file is empty
  if (! logfile.size()) {

    // write title
    Serial.println("CSV File created.");
    logfile.println("Title text");

  }

This last option was actually what I was originally looking for! I will however probably stick with the option I suggested since it works pretty well after having added the close() lines. The title is actually the name of the variables which will be printed within the file, one for every column, so it is quite necessary.

Thanks a lot! Cheers