]> git.piffa.net Git - arduino/blob - books/pdummies/Libraries/SD/utility/SdFile.cpp
first commit
[arduino] / books / pdummies / Libraries / SD / utility / SdFile.cpp
1 /* Arduino SdFat Library
2  * Copyright (C) 2009 by William Greiman
3  *
4  * This file is part of the Arduino SdFat Library
5  *
6  * This Library is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation, either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * This Library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with the Arduino SdFat Library.  If not, see
18  * <http://www.gnu.org/licenses/>.
19  */
20 #include <SdFat.h>
21 #include <avr/pgmspace.h>
22 #if ARDUINO >= 100
23  #include "Arduino.h"
24 #else
25  #include "WProgram.h"
26 #endif
27 //------------------------------------------------------------------------------
28 // callback function for date/time
29 void (*SdFile::dateTime_)(uint16_t* date, uint16_t* time) = NULL;
30
31 #if ALLOW_DEPRECATED_FUNCTIONS
32 // suppress cpplint warnings with NOLINT comment
33 void (*SdFile::oldDateTime_)(uint16_t& date, uint16_t& time) = NULL;  // NOLINT
34 #endif  // ALLOW_DEPRECATED_FUNCTIONS
35 //------------------------------------------------------------------------------
36 // add a cluster to a file
37 uint8_t SdFile::addCluster() {
38   if (!vol_->allocContiguous(1, &curCluster_)) return false;
39
40   // if first cluster of file link to directory entry
41   if (firstCluster_ == 0) {
42     firstCluster_ = curCluster_;
43     flags_ |= F_FILE_DIR_DIRTY;
44   }
45   return true;
46 }
47 //------------------------------------------------------------------------------
48 // Add a cluster to a directory file and zero the cluster.
49 // return with first block of cluster in the cache
50 uint8_t SdFile::addDirCluster(void) {
51   if (!addCluster()) return false;
52
53   // zero data in cluster insure first cluster is in cache
54   uint32_t block = vol_->clusterStartBlock(curCluster_);
55   for (uint8_t i = vol_->blocksPerCluster_; i != 0; i--) {
56     if (!SdVolume::cacheZeroBlock(block + i - 1)) return false;
57   }
58   // Increase directory file size by cluster size
59   fileSize_ += 512UL << vol_->clusterSizeShift_;
60   return true;
61 }
62 //------------------------------------------------------------------------------
63 // cache a file's directory entry
64 // return pointer to cached entry or null for failure
65 dir_t* SdFile::cacheDirEntry(uint8_t action) {
66   if (!SdVolume::cacheRawBlock(dirBlock_, action)) return NULL;
67   return SdVolume::cacheBuffer_.dir + dirIndex_;
68 }
69 //------------------------------------------------------------------------------
70 /**
71  *  Close a file and force cached data and directory information
72  *  to be written to the storage device.
73  *
74  * \return The value one, true, is returned for success and
75  * the value zero, false, is returned for failure.
76  * Reasons for failure include no file is open or an I/O error.
77  */
78 uint8_t SdFile::close(void) {
79   if (!sync())return false;
80   type_ = FAT_FILE_TYPE_CLOSED;
81   return true;
82 }
83 //------------------------------------------------------------------------------
84 /**
85  * Check for contiguous file and return its raw block range.
86  *
87  * \param[out] bgnBlock the first block address for the file.
88  * \param[out] endBlock the last  block address for the file.
89  *
90  * \return The value one, true, is returned for success and
91  * the value zero, false, is returned for failure.
92  * Reasons for failure include file is not contiguous, file has zero length
93  * or an I/O error occurred.
94  */
95 uint8_t SdFile::contiguousRange(uint32_t* bgnBlock, uint32_t* endBlock) {
96   // error if no blocks
97   if (firstCluster_ == 0) return false;
98
99   for (uint32_t c = firstCluster_; ; c++) {
100     uint32_t next;
101     if (!vol_->fatGet(c, &next)) return false;
102
103     // check for contiguous
104     if (next != (c + 1)) {
105       // error if not end of chain
106       if (!vol_->isEOC(next)) return false;
107       *bgnBlock = vol_->clusterStartBlock(firstCluster_);
108       *endBlock = vol_->clusterStartBlock(c)
109                   + vol_->blocksPerCluster_ - 1;
110       return true;
111     }
112   }
113 }
114 //------------------------------------------------------------------------------
115 /**
116  * Create and open a new contiguous file of a specified size.
117  *
118  * \note This function only supports short DOS 8.3 names.
119  * See open() for more information.
120  *
121  * \param[in] dirFile The directory where the file will be created.
122  * \param[in] fileName A valid DOS 8.3 file name.
123  * \param[in] size The desired file size.
124  *
125  * \return The value one, true, is returned for success and
126  * the value zero, false, is returned for failure.
127  * Reasons for failure include \a fileName contains
128  * an invalid DOS 8.3 file name, the FAT volume has not been initialized,
129  * a file is already open, the file already exists, the root
130  * directory is full or an I/O error.
131  *
132  */
133 uint8_t SdFile::createContiguous(SdFile* dirFile,
134         const char* fileName, uint32_t size) {
135   // don't allow zero length file
136   if (size == 0) return false;
137   if (!open(dirFile, fileName, O_CREAT | O_EXCL | O_RDWR)) return false;
138
139   // calculate number of clusters needed
140   uint32_t count = ((size - 1) >> (vol_->clusterSizeShift_ + 9)) + 1;
141
142   // allocate clusters
143   if (!vol_->allocContiguous(count, &firstCluster_)) {
144     remove();
145     return false;
146   }
147   fileSize_ = size;
148
149   // insure sync() will update dir entry
150   flags_ |= F_FILE_DIR_DIRTY;
151   return sync();
152 }
153 //------------------------------------------------------------------------------
154 /**
155  * Return a files directory entry
156  *
157  * \param[out] dir Location for return of the files directory entry.
158  *
159  * \return The value one, true, is returned for success and
160  * the value zero, false, is returned for failure.
161  */
162 uint8_t SdFile::dirEntry(dir_t* dir) {
163   // make sure fields on SD are correct
164   if (!sync()) return false;
165
166   // read entry
167   dir_t* p = cacheDirEntry(SdVolume::CACHE_FOR_READ);
168   if (!p) return false;
169
170   // copy to caller's struct
171   memcpy(dir, p, sizeof(dir_t));
172   return true;
173 }
174 //------------------------------------------------------------------------------
175 /**
176  * Format the name field of \a dir into the 13 byte array
177  * \a name in standard 8.3 short name format.
178  *
179  * \param[in] dir The directory structure containing the name.
180  * \param[out] name A 13 byte char array for the formatted name.
181  */
182 void SdFile::dirName(const dir_t& dir, char* name) {
183   uint8_t j = 0;
184   for (uint8_t i = 0; i < 11; i++) {
185     if (dir.name[i] == ' ')continue;
186     if (i == 8) name[j++] = '.';
187     name[j++] = dir.name[i];
188   }
189   name[j] = 0;
190 }
191 //------------------------------------------------------------------------------
192 /** List directory contents to Serial.
193  *
194  * \param[in] flags The inclusive OR of
195  *
196  * LS_DATE - %Print file modification date
197  *
198  * LS_SIZE - %Print file size.
199  *
200  * LS_R - Recursive list of subdirectories.
201  *
202  * \param[in] indent Amount of space before file name. Used for recursive
203  * list to indicate subdirectory level.
204  */
205 void SdFile::ls(uint8_t flags, uint8_t indent) {
206   dir_t* p;
207
208   rewind();
209   while ((p = readDirCache())) {
210     // done if past last used entry
211     if (p->name[0] == DIR_NAME_FREE) break;
212
213     // skip deleted entry and entries for . and  ..
214     if (p->name[0] == DIR_NAME_DELETED || p->name[0] == '.') continue;
215
216     // only list subdirectories and files
217     if (!DIR_IS_FILE_OR_SUBDIR(p)) continue;
218
219     // print any indent spaces
220     for (int8_t i = 0; i < indent; i++) Serial.print(' ');
221
222     // print file name with possible blank fill
223     printDirName(*p, flags & (LS_DATE | LS_SIZE) ? 14 : 0);
224
225     // print modify date/time if requested
226     if (flags & LS_DATE) {
227        printFatDate(p->lastWriteDate);
228        Serial.print(' ');
229        printFatTime(p->lastWriteTime);
230     }
231     // print size if requested
232     if (!DIR_IS_SUBDIR(p) && (flags & LS_SIZE)) {
233       Serial.print(' ');
234       Serial.print(p->fileSize);
235     }
236     Serial.println();
237
238     // list subdirectory content if requested
239     if ((flags & LS_R) && DIR_IS_SUBDIR(p)) {
240       uint16_t index = curPosition()/32 - 1;
241       SdFile s;
242       if (s.open(this, index, O_READ)) s.ls(flags, indent + 2);
243       seekSet(32 * (index + 1));
244     }
245   }
246 }
247 //------------------------------------------------------------------------------
248 // format directory name field from a 8.3 name string
249 uint8_t SdFile::make83Name(const char* str, uint8_t* name) {
250   uint8_t c;
251   uint8_t n = 7;  // max index for part before dot
252   uint8_t i = 0;
253   // blank fill name and extension
254   while (i < 11) name[i++] = ' ';
255   i = 0;
256   while ((c = *str++) != '\0') {
257     if (c == '.') {
258       if (n == 10) return false;  // only one dot allowed
259       n = 10;  // max index for full 8.3 name
260       i = 8;   // place for extension
261     } else {
262       // illegal FAT characters
263       PGM_P p = PSTR("|<>^+=?/[];,*\"\\");
264       uint8_t b;
265       while ((b = pgm_read_byte(p++))) if (b == c) return false;
266       // check size and only allow ASCII printable characters
267       if (i > n || c < 0X21 || c > 0X7E)return false;
268       // only upper case allowed in 8.3 names - convert lower to upper
269       name[i++] = c < 'a' || c > 'z' ?  c : c + ('A' - 'a');
270     }
271   }
272   // must have a file name, extension is optional
273   return name[0] != ' ';
274 }
275 //------------------------------------------------------------------------------
276 /** Make a new directory.
277  *
278  * \param[in] dir An open SdFat instance for the directory that will containing
279  * the new directory.
280  *
281  * \param[in] dirName A valid 8.3 DOS name for the new directory.
282  *
283  * \return The value one, true, is returned for success and
284  * the value zero, false, is returned for failure.
285  * Reasons for failure include this SdFile is already open, \a dir is not a
286  * directory, \a dirName is invalid or already exists in \a dir.
287  */
288 uint8_t SdFile::makeDir(SdFile* dir, const char* dirName) {
289   dir_t d;
290
291   // create a normal file
292   if (!open(dir, dirName, O_CREAT | O_EXCL | O_RDWR)) return false;
293
294   // convert SdFile to directory
295   flags_ = O_READ;
296   type_ = FAT_FILE_TYPE_SUBDIR;
297
298   // allocate and zero first cluster
299   if (!addDirCluster())return false;
300
301   // force entry to SD
302   if (!sync()) return false;
303
304   // cache entry - should already be in cache due to sync() call
305   dir_t* p = cacheDirEntry(SdVolume::CACHE_FOR_WRITE);
306   if (!p) return false;
307
308   // change directory entry  attribute
309   p->attributes = DIR_ATT_DIRECTORY;
310
311   // make entry for '.'
312   memcpy(&d, p, sizeof(d));
313   for (uint8_t i = 1; i < 11; i++) d.name[i] = ' ';
314   d.name[0] = '.';
315
316   // cache block for '.'  and '..'
317   uint32_t block = vol_->clusterStartBlock(firstCluster_);
318   if (!SdVolume::cacheRawBlock(block, SdVolume::CACHE_FOR_WRITE)) return false;
319
320   // copy '.' to block
321   memcpy(&SdVolume::cacheBuffer_.dir[0], &d, sizeof(d));
322
323   // make entry for '..'
324   d.name[1] = '.';
325   if (dir->isRoot()) {
326     d.firstClusterLow = 0;
327     d.firstClusterHigh = 0;
328   } else {
329     d.firstClusterLow = dir->firstCluster_ & 0XFFFF;
330     d.firstClusterHigh = dir->firstCluster_ >> 16;
331   }
332   // copy '..' to block
333   memcpy(&SdVolume::cacheBuffer_.dir[1], &d, sizeof(d));
334
335   // set position after '..'
336   curPosition_ = 2 * sizeof(d);
337
338   // write first block
339   return SdVolume::cacheFlush();
340 }
341 //------------------------------------------------------------------------------
342 /**
343  * Open a file or directory by name.
344  *
345  * \param[in] dirFile An open SdFat instance for the directory containing the
346  * file to be opened.
347  *
348  * \param[in] fileName A valid 8.3 DOS name for a file to be opened.
349  *
350  * \param[in] oflag Values for \a oflag are constructed by a bitwise-inclusive
351  * OR of flags from the following list
352  *
353  * O_READ - Open for reading.
354  *
355  * O_RDONLY - Same as O_READ.
356  *
357  * O_WRITE - Open for writing.
358  *
359  * O_WRONLY - Same as O_WRITE.
360  *
361  * O_RDWR - Open for reading and writing.
362  *
363  * O_APPEND - If set, the file offset shall be set to the end of the
364  * file prior to each write.
365  *
366  * O_CREAT - If the file exists, this flag has no effect except as noted
367  * under O_EXCL below. Otherwise, the file shall be created
368  *
369  * O_EXCL - If O_CREAT and O_EXCL are set, open() shall fail if the file exists.
370  *
371  * O_SYNC - Call sync() after each write.  This flag should not be used with
372  * write(uint8_t), write_P(PGM_P), writeln_P(PGM_P), or the Arduino Print class.
373  * These functions do character at a time writes so sync() will be called
374  * after each byte.
375  *
376  * O_TRUNC - If the file exists and is a regular file, and the file is
377  * successfully opened and is not read only, its length shall be truncated to 0.
378  *
379  * \note Directory files must be opened read only.  Write and truncation is
380  * not allowed for directory files.
381  *
382  * \return The value one, true, is returned for success and
383  * the value zero, false, is returned for failure.
384  * Reasons for failure include this SdFile is already open, \a difFile is not
385  * a directory, \a fileName is invalid, the file does not exist
386  * or can't be opened in the access mode specified by oflag.
387  */
388 uint8_t SdFile::open(SdFile* dirFile, const char* fileName, uint8_t oflag) {
389   uint8_t dname[11];
390   dir_t* p;
391
392   // error if already open
393   if (isOpen())return false;
394
395   if (!make83Name(fileName, dname)) return false;
396   vol_ = dirFile->vol_;
397   dirFile->rewind();
398
399   // bool for empty entry found
400   uint8_t emptyFound = false;
401
402   // search for file
403   while (dirFile->curPosition_ < dirFile->fileSize_) {
404     uint8_t index = 0XF & (dirFile->curPosition_ >> 5);
405     p = dirFile->readDirCache();
406     if (p == NULL) return false;
407
408     if (p->name[0] == DIR_NAME_FREE || p->name[0] == DIR_NAME_DELETED) {
409       // remember first empty slot
410       if (!emptyFound) {
411         emptyFound = true;
412         dirIndex_ = index;
413         dirBlock_ = SdVolume::cacheBlockNumber_;
414       }
415       // done if no entries follow
416       if (p->name[0] == DIR_NAME_FREE) break;
417     } else if (!memcmp(dname, p->name, 11)) {
418       // don't open existing file if O_CREAT and O_EXCL
419       if ((oflag & (O_CREAT | O_EXCL)) == (O_CREAT | O_EXCL)) return false;
420
421       // open found file
422       return openCachedEntry(0XF & index, oflag);
423     }
424   }
425   // only create file if O_CREAT and O_WRITE
426   if ((oflag & (O_CREAT | O_WRITE)) != (O_CREAT | O_WRITE)) return false;
427
428   // cache found slot or add cluster if end of file
429   if (emptyFound) {
430     p = cacheDirEntry(SdVolume::CACHE_FOR_WRITE);
431     if (!p) return false;
432   } else {
433     if (dirFile->type_ == FAT_FILE_TYPE_ROOT16) return false;
434
435     // add and zero cluster for dirFile - first cluster is in cache for write
436     if (!dirFile->addDirCluster()) return false;
437
438     // use first entry in cluster
439     dirIndex_ = 0;
440     p = SdVolume::cacheBuffer_.dir;
441   }
442   // initialize as empty file
443   memset(p, 0, sizeof(dir_t));
444   memcpy(p->name, dname, 11);
445
446   // set timestamps
447   if (dateTime_) {
448     // call user function
449     dateTime_(&p->creationDate, &p->creationTime);
450   } else {
451     // use default date/time
452     p->creationDate = FAT_DEFAULT_DATE;
453     p->creationTime = FAT_DEFAULT_TIME;
454   }
455   p->lastAccessDate = p->creationDate;
456   p->lastWriteDate = p->creationDate;
457   p->lastWriteTime = p->creationTime;
458
459   // force write of entry to SD
460   if (!SdVolume::cacheFlush()) return false;
461
462   // open entry in cache
463   return openCachedEntry(dirIndex_, oflag);
464 }
465 //------------------------------------------------------------------------------
466 /**
467  * Open a file by index.
468  *
469  * \param[in] dirFile An open SdFat instance for the directory.
470  *
471  * \param[in] index The \a index of the directory entry for the file to be
472  * opened.  The value for \a index is (directory file position)/32.
473  *
474  * \param[in] oflag Values for \a oflag are constructed by a bitwise-inclusive
475  * OR of flags O_READ, O_WRITE, O_TRUNC, and O_SYNC.
476  *
477  * See open() by fileName for definition of flags and return values.
478  *
479  */
480 uint8_t SdFile::open(SdFile* dirFile, uint16_t index, uint8_t oflag) {
481   // error if already open
482   if (isOpen())return false;
483
484   // don't open existing file if O_CREAT and O_EXCL - user call error
485   if ((oflag & (O_CREAT | O_EXCL)) == (O_CREAT | O_EXCL)) return false;
486
487   vol_ = dirFile->vol_;
488
489   // seek to location of entry
490   if (!dirFile->seekSet(32 * index)) return false;
491
492   // read entry into cache
493   dir_t* p = dirFile->readDirCache();
494   if (p == NULL) return false;
495
496   // error if empty slot or '.' or '..'
497   if (p->name[0] == DIR_NAME_FREE ||
498       p->name[0] == DIR_NAME_DELETED || p->name[0] == '.') {
499     return false;
500   }
501   // open cached entry
502   return openCachedEntry(index & 0XF, oflag);
503 }
504 //------------------------------------------------------------------------------
505 // open a cached directory entry. Assumes vol_ is initializes
506 uint8_t SdFile::openCachedEntry(uint8_t dirIndex, uint8_t oflag) {
507   // location of entry in cache
508   dir_t* p = SdVolume::cacheBuffer_.dir + dirIndex;
509
510   // write or truncate is an error for a directory or read-only file
511   if (p->attributes & (DIR_ATT_READ_ONLY | DIR_ATT_DIRECTORY)) {
512     if (oflag & (O_WRITE | O_TRUNC)) return false;
513   }
514   // remember location of directory entry on SD
515   dirIndex_ = dirIndex;
516   dirBlock_ = SdVolume::cacheBlockNumber_;
517
518   // copy first cluster number for directory fields
519   firstCluster_ = (uint32_t)p->firstClusterHigh << 16;
520   firstCluster_ |= p->firstClusterLow;
521
522   // make sure it is a normal file or subdirectory
523   if (DIR_IS_FILE(p)) {
524     fileSize_ = p->fileSize;
525     type_ = FAT_FILE_TYPE_NORMAL;
526   } else if (DIR_IS_SUBDIR(p)) {
527     if (!vol_->chainSize(firstCluster_, &fileSize_)) return false;
528     type_ = FAT_FILE_TYPE_SUBDIR;
529   } else {
530     return false;
531   }
532   // save open flags for read/write
533   flags_ = oflag & (O_ACCMODE | O_SYNC | O_APPEND);
534
535   // set to start of file
536   curCluster_ = 0;
537   curPosition_ = 0;
538
539   // truncate file to zero length if requested
540   if (oflag & O_TRUNC) return truncate(0);
541   return true;
542 }
543 //------------------------------------------------------------------------------
544 /**
545  * Open a volume's root directory.
546  *
547  * \param[in] vol The FAT volume containing the root directory to be opened.
548  *
549  * \return The value one, true, is returned for success and
550  * the value zero, false, is returned for failure.
551  * Reasons for failure include the FAT volume has not been initialized
552  * or it a FAT12 volume.
553  */
554 uint8_t SdFile::openRoot(SdVolume* vol) {
555   // error if file is already open
556   if (isOpen()) return false;
557
558   if (vol->fatType() == 16) {
559     type_ = FAT_FILE_TYPE_ROOT16;
560     firstCluster_ = 0;
561     fileSize_ = 32 * vol->rootDirEntryCount();
562   } else if (vol->fatType() == 32) {
563     type_ = FAT_FILE_TYPE_ROOT32;
564     firstCluster_ = vol->rootDirStart();
565     if (!vol->chainSize(firstCluster_, &fileSize_)) return false;
566   } else {
567     // volume is not initialized or FAT12
568     return false;
569   }
570   vol_ = vol;
571   // read only
572   flags_ = O_READ;
573
574   // set to start of file
575   curCluster_ = 0;
576   curPosition_ = 0;
577
578   // root has no directory entry
579   dirBlock_ = 0;
580   dirIndex_ = 0;
581   return true;
582 }
583 //------------------------------------------------------------------------------
584 /** %Print the name field of a directory entry in 8.3 format to Serial.
585  *
586  * \param[in] dir The directory structure containing the name.
587  * \param[in] width Blank fill name if length is less than \a width.
588  */
589 void SdFile::printDirName(const dir_t& dir, uint8_t width) {
590   uint8_t w = 0;
591   for (uint8_t i = 0; i < 11; i++) {
592     if (dir.name[i] == ' ')continue;
593     if (i == 8) {
594       Serial.print('.');
595       w++;
596     }
597 #if ARDUINO >= 100
598     Serial.write(dir.name[i]);
599 #else
600     Serial.print(dir.name[i]);
601 #endif
602     w++;
603   }
604   if (DIR_IS_SUBDIR(&dir)) {
605     Serial.print('/');
606     w++;
607   }
608   while (w < width) {
609     Serial.print(' ');
610     w++;
611   }
612 }
613 //------------------------------------------------------------------------------
614 /** %Print a directory date field to Serial.
615  *
616  *  Format is yyyy-mm-dd.
617  *
618  * \param[in] fatDate The date field from a directory entry.
619  */
620 void SdFile::printFatDate(uint16_t fatDate) {
621   Serial.print(FAT_YEAR(fatDate));
622   Serial.print('-');
623   printTwoDigits(FAT_MONTH(fatDate));
624   Serial.print('-');
625   printTwoDigits(FAT_DAY(fatDate));
626 }
627 //------------------------------------------------------------------------------
628 /** %Print a directory time field to Serial.
629  *
630  * Format is hh:mm:ss.
631  *
632  * \param[in] fatTime The time field from a directory entry.
633  */
634 void SdFile::printFatTime(uint16_t fatTime) {
635   printTwoDigits(FAT_HOUR(fatTime));
636   Serial.print(':');
637   printTwoDigits(FAT_MINUTE(fatTime));
638   Serial.print(':');
639   printTwoDigits(FAT_SECOND(fatTime));
640 }
641 //------------------------------------------------------------------------------
642 /** %Print a value as two digits to Serial.
643  *
644  * \param[in] v Value to be printed, 0 <= \a v <= 99
645  */
646 void SdFile::printTwoDigits(uint8_t v) {
647   char str[3];
648   str[0] = '0' + v/10;
649   str[1] = '0' + v % 10;
650   str[2] = 0;
651   Serial.print(str);
652 }
653 //------------------------------------------------------------------------------
654 /**
655  * Read data from a file starting at the current position.
656  *
657  * \param[out] buf Pointer to the location that will receive the data.
658  *
659  * \param[in] nbyte Maximum number of bytes to read.
660  *
661  * \return For success read() returns the number of bytes read.
662  * A value less than \a nbyte, including zero, will be returned
663  * if end of file is reached.
664  * If an error occurs, read() returns -1.  Possible errors include
665  * read() called before a file has been opened, corrupt file system
666  * or an I/O error occurred.
667  */
668 int16_t SdFile::read(void* buf, uint16_t nbyte) {
669   uint8_t* dst = reinterpret_cast<uint8_t*>(buf);
670
671   // error if not open or write only
672   if (!isOpen() || !(flags_ & O_READ)) return -1;
673
674   // max bytes left in file
675   if (nbyte > (fileSize_ - curPosition_)) nbyte = fileSize_ - curPosition_;
676
677   // amount left to read
678   uint16_t toRead = nbyte;
679   while (toRead > 0) {
680     uint32_t block;  // raw device block number
681     uint16_t offset = curPosition_ & 0X1FF;  // offset in block
682     if (type_ == FAT_FILE_TYPE_ROOT16) {
683       block = vol_->rootDirStart() + (curPosition_ >> 9);
684     } else {
685       uint8_t blockOfCluster = vol_->blockOfCluster(curPosition_);
686       if (offset == 0 && blockOfCluster == 0) {
687         // start of new cluster
688         if (curPosition_ == 0) {
689           // use first cluster in file
690           curCluster_ = firstCluster_;
691         } else {
692           // get next cluster from FAT
693           if (!vol_->fatGet(curCluster_, &curCluster_)) return -1;
694         }
695       }
696       block = vol_->clusterStartBlock(curCluster_) + blockOfCluster;
697     }
698     uint16_t n = toRead;
699
700     // amount to be read from current block
701     if (n > (512 - offset)) n = 512 - offset;
702
703     // no buffering needed if n == 512 or user requests no buffering
704     if ((unbufferedRead() || n == 512) &&
705       block != SdVolume::cacheBlockNumber_) {
706       if (!vol_->readData(block, offset, n, dst)) return -1;
707       dst += n;
708     } else {
709       // read block to cache and copy data to caller
710       if (!SdVolume::cacheRawBlock(block, SdVolume::CACHE_FOR_READ)) return -1;
711       uint8_t* src = SdVolume::cacheBuffer_.data + offset;
712       uint8_t* end = src + n;
713       while (src != end) *dst++ = *src++;
714     }
715     curPosition_ += n;
716     toRead -= n;
717   }
718   return nbyte;
719 }
720 //------------------------------------------------------------------------------
721 /**
722  * Read the next directory entry from a directory file.
723  *
724  * \param[out] dir The dir_t struct that will receive the data.
725  *
726  * \return For success readDir() returns the number of bytes read.
727  * A value of zero will be returned if end of file is reached.
728  * If an error occurs, readDir() returns -1.  Possible errors include
729  * readDir() called before a directory has been opened, this is not
730  * a directory file or an I/O error occurred.
731  */
732 int8_t SdFile::readDir(dir_t* dir) {
733   int8_t n;
734   // if not a directory file or miss-positioned return an error
735   if (!isDir() || (0X1F & curPosition_)) return -1;
736
737   while ((n = read(dir, sizeof(dir_t))) == sizeof(dir_t)) {
738     // last entry if DIR_NAME_FREE
739     if (dir->name[0] == DIR_NAME_FREE) break;
740     // skip empty entries and entry for .  and ..
741     if (dir->name[0] == DIR_NAME_DELETED || dir->name[0] == '.') continue;
742     // return if normal file or subdirectory
743     if (DIR_IS_FILE_OR_SUBDIR(dir)) return n;
744   }
745   // error, end of file, or past last entry
746   return n < 0 ? -1 : 0;
747 }
748 //------------------------------------------------------------------------------
749 // Read next directory entry into the cache
750 // Assumes file is correctly positioned
751 dir_t* SdFile::readDirCache(void) {
752   // error if not directory
753   if (!isDir()) return NULL;
754
755   // index of entry in cache
756   uint8_t i = (curPosition_ >> 5) & 0XF;
757
758   // use read to locate and cache block
759   if (read() < 0) return NULL;
760
761   // advance to next entry
762   curPosition_ += 31;
763
764   // return pointer to entry
765   return (SdVolume::cacheBuffer_.dir + i);
766 }
767 //------------------------------------------------------------------------------
768 /**
769  * Remove a file.
770  *
771  * The directory entry and all data for the file are deleted.
772  *
773  * \note This function should not be used to delete the 8.3 version of a
774  * file that has a long name. For example if a file has the long name
775  * "New Text Document.txt" you should not delete the 8.3 name "NEWTEX~1.TXT".
776  *
777  * \return The value one, true, is returned for success and
778  * the value zero, false, is returned for failure.
779  * Reasons for failure include the file read-only, is a directory,
780  * or an I/O error occurred.
781  */
782 uint8_t SdFile::remove(void) {
783   // free any clusters - will fail if read-only or directory
784   if (!truncate(0)) return false;
785
786   // cache directory entry
787   dir_t* d = cacheDirEntry(SdVolume::CACHE_FOR_WRITE);
788   if (!d) return false;
789
790   // mark entry deleted
791   d->name[0] = DIR_NAME_DELETED;
792
793   // set this SdFile closed
794   type_ = FAT_FILE_TYPE_CLOSED;
795
796   // write entry to SD
797   return SdVolume::cacheFlush();
798 }
799 //------------------------------------------------------------------------------
800 /**
801  * Remove a file.
802  *
803  * The directory entry and all data for the file are deleted.
804  *
805  * \param[in] dirFile The directory that contains the file.
806  * \param[in] fileName The name of the file to be removed.
807  *
808  * \note This function should not be used to delete the 8.3 version of a
809  * file that has a long name. For example if a file has the long name
810  * "New Text Document.txt" you should not delete the 8.3 name "NEWTEX~1.TXT".
811  *
812  * \return The value one, true, is returned for success and
813  * the value zero, false, is returned for failure.
814  * Reasons for failure include the file is a directory, is read only,
815  * \a dirFile is not a directory, \a fileName is not found
816  * or an I/O error occurred.
817  */
818 uint8_t SdFile::remove(SdFile* dirFile, const char* fileName) {
819   SdFile file;
820   if (!file.open(dirFile, fileName, O_WRITE)) return false;
821   return file.remove();
822 }
823 //------------------------------------------------------------------------------
824 /** Remove a directory file.
825  *
826  * The directory file will be removed only if it is empty and is not the
827  * root directory.  rmDir() follows DOS and Windows and ignores the
828  * read-only attribute for the directory.
829  *
830  * \note This function should not be used to delete the 8.3 version of a
831  * directory that has a long name. For example if a directory has the
832  * long name "New folder" you should not delete the 8.3 name "NEWFOL~1".
833  *
834  * \return The value one, true, is returned for success and
835  * the value zero, false, is returned for failure.
836  * Reasons for failure include the file is not a directory, is the root
837  * directory, is not empty, or an I/O error occurred.
838  */
839 uint8_t SdFile::rmDir(void) {
840   // must be open subdirectory
841   if (!isSubDir()) return false;
842
843   rewind();
844
845   // make sure directory is empty
846   while (curPosition_ < fileSize_) {
847     dir_t* p = readDirCache();
848     if (p == NULL) return false;
849     // done if past last used entry
850     if (p->name[0] == DIR_NAME_FREE) break;
851     // skip empty slot or '.' or '..'
852     if (p->name[0] == DIR_NAME_DELETED || p->name[0] == '.') continue;
853     // error not empty
854     if (DIR_IS_FILE_OR_SUBDIR(p)) return false;
855   }
856   // convert empty directory to normal file for remove
857   type_ = FAT_FILE_TYPE_NORMAL;
858   flags_ |= O_WRITE;
859   return remove();
860 }
861 //------------------------------------------------------------------------------
862 /** Recursively delete a directory and all contained files.
863  *
864  * This is like the Unix/Linux 'rm -rf *' if called with the root directory
865  * hence the name.
866  *
867  * Warning - This will remove all contents of the directory including
868  * subdirectories.  The directory will then be removed if it is not root.
869  * The read-only attribute for files will be ignored.
870  *
871  * \note This function should not be used to delete the 8.3 version of
872  * a directory that has a long name.  See remove() and rmDir().
873  *
874  * \return The value one, true, is returned for success and
875  * the value zero, false, is returned for failure.
876  */
877 uint8_t SdFile::rmRfStar(void) {
878   rewind();
879   while (curPosition_ < fileSize_) {
880     SdFile f;
881
882     // remember position
883     uint16_t index = curPosition_/32;
884
885     dir_t* p = readDirCache();
886     if (!p) return false;
887
888     // done if past last entry
889     if (p->name[0] == DIR_NAME_FREE) break;
890
891     // skip empty slot or '.' or '..'
892     if (p->name[0] == DIR_NAME_DELETED || p->name[0] == '.') continue;
893
894     // skip if part of long file name or volume label in root
895     if (!DIR_IS_FILE_OR_SUBDIR(p)) continue;
896
897     if (!f.open(this, index, O_READ)) return false;
898     if (f.isSubDir()) {
899       // recursively delete
900       if (!f.rmRfStar()) return false;
901     } else {
902       // ignore read-only
903       f.flags_ |= O_WRITE;
904       if (!f.remove()) return false;
905     }
906     // position to next entry if required
907     if (curPosition_ != (32*(index + 1))) {
908       if (!seekSet(32*(index + 1))) return false;
909     }
910   }
911   // don't try to delete root
912   if (isRoot()) return true;
913   return rmDir();
914 }
915 //------------------------------------------------------------------------------
916 /**
917  * Sets a file's position.
918  *
919  * \param[in] pos The new position in bytes from the beginning of the file.
920  *
921  * \return The value one, true, is returned for success and
922  * the value zero, false, is returned for failure.
923  */
924 uint8_t SdFile::seekSet(uint32_t pos) {
925   // error if file not open or seek past end of file
926   if (!isOpen() || pos > fileSize_) return false;
927
928   if (type_ == FAT_FILE_TYPE_ROOT16) {
929     curPosition_ = pos;
930     return true;
931   }
932   if (pos == 0) {
933     // set position to start of file
934     curCluster_ = 0;
935     curPosition_ = 0;
936     return true;
937   }
938   // calculate cluster index for cur and new position
939   uint32_t nCur = (curPosition_ - 1) >> (vol_->clusterSizeShift_ + 9);
940   uint32_t nNew = (pos - 1) >> (vol_->clusterSizeShift_ + 9);
941
942   if (nNew < nCur || curPosition_ == 0) {
943     // must follow chain from first cluster
944     curCluster_ = firstCluster_;
945   } else {
946     // advance from curPosition
947     nNew -= nCur;
948   }
949   while (nNew--) {
950     if (!vol_->fatGet(curCluster_, &curCluster_)) return false;
951   }
952   curPosition_ = pos;
953   return true;
954 }
955 //------------------------------------------------------------------------------
956 /**
957  * The sync() call causes all modified data and directory fields
958  * to be written to the storage device.
959  *
960  * \return The value one, true, is returned for success and
961  * the value zero, false, is returned for failure.
962  * Reasons for failure include a call to sync() before a file has been
963  * opened or an I/O error.
964  */
965 uint8_t SdFile::sync(void) {
966   // only allow open files and directories
967   if (!isOpen()) return false;
968
969   if (flags_ & F_FILE_DIR_DIRTY) {
970     dir_t* d = cacheDirEntry(SdVolume::CACHE_FOR_WRITE);
971     if (!d) return false;
972
973     // do not set filesize for dir files
974     if (!isDir()) d->fileSize = fileSize_;
975
976     // update first cluster fields
977     d->firstClusterLow = firstCluster_ & 0XFFFF;
978     d->firstClusterHigh = firstCluster_ >> 16;
979
980     // set modify time if user supplied a callback date/time function
981     if (dateTime_) {
982       dateTime_(&d->lastWriteDate, &d->lastWriteTime);
983       d->lastAccessDate = d->lastWriteDate;
984     }
985     // clear directory dirty
986     flags_ &= ~F_FILE_DIR_DIRTY;
987   }
988   return SdVolume::cacheFlush();
989 }
990 //------------------------------------------------------------------------------
991 /**
992  * Set a file's timestamps in its directory entry.
993  *
994  * \param[in] flags Values for \a flags are constructed by a bitwise-inclusive
995  * OR of flags from the following list
996  *
997  * T_ACCESS - Set the file's last access date.
998  *
999  * T_CREATE - Set the file's creation date and time.
1000  *
1001  * T_WRITE - Set the file's last write/modification date and time.
1002  *
1003  * \param[in] year Valid range 1980 - 2107 inclusive.
1004  *
1005  * \param[in] month Valid range 1 - 12 inclusive.
1006  *
1007  * \param[in] day Valid range 1 - 31 inclusive.
1008  *
1009  * \param[in] hour Valid range 0 - 23 inclusive.
1010  *
1011  * \param[in] minute Valid range 0 - 59 inclusive.
1012  *
1013  * \param[in] second Valid range 0 - 59 inclusive
1014  *
1015  * \note It is possible to set an invalid date since there is no check for
1016  * the number of days in a month.
1017  *
1018  * \note
1019  * Modify and access timestamps may be overwritten if a date time callback
1020  * function has been set by dateTimeCallback().
1021  *
1022  * \return The value one, true, is returned for success and
1023  * the value zero, false, is returned for failure.
1024  */
1025 uint8_t SdFile::timestamp(uint8_t flags, uint16_t year, uint8_t month,
1026          uint8_t day, uint8_t hour, uint8_t minute, uint8_t second) {
1027   if (!isOpen()
1028     || year < 1980
1029     || year > 2107
1030     || month < 1
1031     || month > 12
1032     || day < 1
1033     || day > 31
1034     || hour > 23
1035     || minute > 59
1036     || second > 59) {
1037       return false;
1038   }
1039   dir_t* d = cacheDirEntry(SdVolume::CACHE_FOR_WRITE);
1040   if (!d) return false;
1041
1042   uint16_t dirDate = FAT_DATE(year, month, day);
1043   uint16_t dirTime = FAT_TIME(hour, minute, second);
1044   if (flags & T_ACCESS) {
1045     d->lastAccessDate = dirDate;
1046   }
1047   if (flags & T_CREATE) {
1048     d->creationDate = dirDate;
1049     d->creationTime = dirTime;
1050     // seems to be units of 1/100 second not 1/10 as Microsoft states
1051     d->creationTimeTenths = second & 1 ? 100 : 0;
1052   }
1053   if (flags & T_WRITE) {
1054     d->lastWriteDate = dirDate;
1055     d->lastWriteTime = dirTime;
1056   }
1057   SdVolume::cacheSetDirty();
1058   return sync();
1059 }
1060 //------------------------------------------------------------------------------
1061 /**
1062  * Truncate a file to a specified length.  The current file position
1063  * will be maintained if it is less than or equal to \a length otherwise
1064  * it will be set to end of file.
1065  *
1066  * \param[in] length The desired length for the file.
1067  *
1068  * \return The value one, true, is returned for success and
1069  * the value zero, false, is returned for failure.
1070  * Reasons for failure include file is read only, file is a directory,
1071  * \a length is greater than the current file size or an I/O error occurs.
1072  */
1073 uint8_t SdFile::truncate(uint32_t length) {
1074 // error if not a normal file or read-only
1075   if (!isFile() || !(flags_ & O_WRITE)) return false;
1076
1077   // error if length is greater than current size
1078   if (length > fileSize_) return false;
1079
1080   // fileSize and length are zero - nothing to do
1081   if (fileSize_ == 0) return true;
1082
1083   // remember position for seek after truncation
1084   uint32_t newPos = curPosition_ > length ? length : curPosition_;
1085
1086   // position to last cluster in truncated file
1087   if (!seekSet(length)) return false;
1088
1089   if (length == 0) {
1090     // free all clusters
1091     if (!vol_->freeChain(firstCluster_)) return false;
1092     firstCluster_ = 0;
1093   } else {
1094     uint32_t toFree;
1095     if (!vol_->fatGet(curCluster_, &toFree)) return false;
1096
1097     if (!vol_->isEOC(toFree)) {
1098       // free extra clusters
1099       if (!vol_->freeChain(toFree)) return false;
1100
1101       // current cluster is end of chain
1102       if (!vol_->fatPutEOC(curCluster_)) return false;
1103     }
1104   }
1105   fileSize_ = length;
1106
1107   // need to update directory entry
1108   flags_ |= F_FILE_DIR_DIRTY;
1109
1110   if (!sync()) return false;
1111
1112   // set file to correct position
1113   return seekSet(newPos);
1114 }
1115 //------------------------------------------------------------------------------
1116 /**
1117  * Write data to an open file.
1118  *
1119  * \note Data is moved to the cache but may not be written to the
1120  * storage device until sync() is called.
1121  *
1122  * \param[in] buf Pointer to the location of the data to be written.
1123  *
1124  * \param[in] nbyte Number of bytes to write.
1125  *
1126  * \return For success write() returns the number of bytes written, always
1127  * \a nbyte.  If an error occurs, write() returns -1.  Possible errors
1128  * include write() is called before a file has been opened, write is called
1129  * for a read-only file, device is full, a corrupt file system or an I/O error.
1130  *
1131  */
1132 #if ARDUINO >= 100
1133 size_t SdFile::write(const void* buf, uint16_t nbyte) {
1134 #else
1135 int16_t SdFile::write(const void* buf, uint16_t nbyte) {
1136 #endif
1137   // convert void* to uint8_t*  -  must be before goto statements
1138   const uint8_t* src = reinterpret_cast<const uint8_t*>(buf);
1139
1140   // number of bytes left to write  -  must be before goto statements
1141   uint16_t nToWrite = nbyte;
1142
1143   // error if not a normal file or is read-only
1144   if (!isFile() || !(flags_ & O_WRITE)) goto writeErrorReturn;
1145
1146   // seek to end of file if append flag
1147   if ((flags_ & O_APPEND) && curPosition_ != fileSize_) {
1148     if (!seekEnd()) goto writeErrorReturn;
1149   }
1150
1151   while (nToWrite > 0) {
1152     uint8_t blockOfCluster = vol_->blockOfCluster(curPosition_);
1153     uint16_t blockOffset = curPosition_ & 0X1FF;
1154     if (blockOfCluster == 0 && blockOffset == 0) {
1155       // start of new cluster
1156       if (curCluster_ == 0) {
1157         if (firstCluster_ == 0) {
1158           // allocate first cluster of file
1159           if (!addCluster()) goto writeErrorReturn;
1160         } else {
1161           curCluster_ = firstCluster_;
1162         }
1163       } else {
1164         uint32_t next;
1165         if (!vol_->fatGet(curCluster_, &next)) return false;
1166         if (vol_->isEOC(next)) {
1167           // add cluster if at end of chain
1168           if (!addCluster()) goto writeErrorReturn;
1169         } else {
1170           curCluster_ = next;
1171         }
1172       }
1173     }
1174     // max space in block
1175     uint16_t n = 512 - blockOffset;
1176
1177     // lesser of space and amount to write
1178     if (n > nToWrite) n = nToWrite;
1179
1180     // block for data write
1181     uint32_t block = vol_->clusterStartBlock(curCluster_) + blockOfCluster;
1182     if (n == 512) {
1183       // full block - don't need to use cache
1184       // invalidate cache if block is in cache
1185       if (SdVolume::cacheBlockNumber_ == block) {
1186         SdVolume::cacheBlockNumber_ = 0XFFFFFFFF;
1187       }
1188       if (!vol_->writeBlock(block, src)) goto writeErrorReturn;
1189       src += 512;
1190     } else {
1191       if (blockOffset == 0 && curPosition_ >= fileSize_) {
1192         // start of new block don't need to read into cache
1193         if (!SdVolume::cacheFlush()) goto writeErrorReturn;
1194         SdVolume::cacheBlockNumber_ = block;
1195         SdVolume::cacheSetDirty();
1196       } else {
1197         // rewrite part of block
1198         if (!SdVolume::cacheRawBlock(block, SdVolume::CACHE_FOR_WRITE)) {
1199           goto writeErrorReturn;
1200         }
1201       }
1202       uint8_t* dst = SdVolume::cacheBuffer_.data + blockOffset;
1203       uint8_t* end = dst + n;
1204       while (dst != end) *dst++ = *src++;
1205     }
1206     nToWrite -= n;
1207     curPosition_ += n;
1208   }
1209   if (curPosition_ > fileSize_) {
1210     // update fileSize and insure sync will update dir entry
1211     fileSize_ = curPosition_;
1212     flags_ |= F_FILE_DIR_DIRTY;
1213   } else if (dateTime_ && nbyte) {
1214     // insure sync will update modified date and time
1215     flags_ |= F_FILE_DIR_DIRTY;
1216   }
1217
1218   if (flags_ & O_SYNC) {
1219     if (!sync()) goto writeErrorReturn;
1220   }
1221   return nbyte;
1222
1223  writeErrorReturn:
1224   // return for write error
1225   writeError = true;
1226   return -1;
1227 }
1228 //------------------------------------------------------------------------------
1229 /**
1230  * Write a byte to a file. Required by the Arduino Print class.
1231  *
1232  * Use SdFile::writeError to check for errors.
1233  */
1234 #if ARDUINO >= 100
1235 size_t SdFile::write(uint8_t b) {
1236   return write(&b, 1);
1237 }
1238 #else
1239 void SdFile::write(uint8_t b) {
1240   write(&b, 1);
1241 }
1242 #endif
1243 //------------------------------------------------------------------------------
1244 /**
1245  * Write a string to a file. Used by the Arduino Print class.
1246  *
1247  * Use SdFile::writeError to check for errors.
1248  */
1249 #if ARDUINO >= 100
1250 size_t SdFile::write(const char* str) {
1251   return write(str, strlen(str));
1252 }
1253 #else
1254 void SdFile::write(const char* str) {
1255   write(str, strlen(str));
1256 }
1257 #endif
1258 //------------------------------------------------------------------------------
1259 /**
1260  * Write a PROGMEM string to a file.
1261  *
1262  * Use SdFile::writeError to check for errors.
1263  */
1264 void SdFile::write_P(PGM_P str) {
1265   for (uint8_t c; (c = pgm_read_byte(str)); str++) write(c);
1266 }
1267 //------------------------------------------------------------------------------
1268 /**
1269  * Write a PROGMEM string followed by CR/LF to a file.
1270  *
1271  * Use SdFile::writeError to check for errors.
1272  */
1273 void SdFile::writeln_P(PGM_P str) {
1274   write_P(str);
1275   println();
1276 }