Pages: [1]   Go Down
Author Topic: Putting File.close() in the right place  (Read 526 times)
0 Members and 1 Guest are viewing this topic.
Offline Offline
Newbie
*
Karma: 0
Posts: 28
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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:
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:
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?
Logged

Sydney, Australia
Offline Offline
Edison Member
*
Karma: 33
Posts: 1273
Big things come in large packages
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

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.
Logged

Arduino libraries http://arduinocode.codeplex.com
Parola hardware & library http://parola.codeplex.com

Pages: [1]   Go Up
Jump to: