Go Down

Topic: Putting File.close() in the right place (Read 563 times) previous topic - next topic

solar_eta

I've recently seen two bits of code that have me confused as to the right place to put the file.close() call in an SD card routine.

Most books seem to favor

Code: [Select]
File dataFile = SD.open(fileName, FILE_WRITE);
          // if the file is available, write to it:
          if (dataFile) {
            dataFile.print(builddatetimestring(systime));
            ...............
            dataFile.close();
            delay(1);
          }
          // if the file isn't open, pop up an error:
          else {
          Serial.println (F("Datafile did not open")); //error opening data2012.csv
          }


Whereas I've also seen
Code: [Select]
File dataFile = SD.open(fileName, FILE_WRITE);
          // if the file is available, write to it:
          if (dataFile) {
            dataFile.print(builddatetimestring(systime));
            ...............
            delay(1);
          }
          // if the file isn't open, pop up an error:
          else {
          Serial.println (F("Datafile did not open")); //error opening data2012.csv
          }
dataFile.close();



I can understand the logic of of the latter which effectively brackets the what your doing to the file with an open /close calls. I see the former as a risk to not closing the file if there is a hiccup in the midle of the routine. But which is right?

marco_c

Strictly speaking th first is correct because you have actually managed to open the file when you are in the 'if' part. However, most libraries are tolerant of files being closed when they were not opened and the second would work as well.
Arduino libraries http://arduinocode.codeplex.com
Parola for Arduino http://parola.codeplex.com

Go Up