1 /* Arduino SdFat Library
2 * Copyright (C) 2009 by William Greiman
4 * This file is part of the Arduino SdFat Library
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.
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.
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/>.
21 #include <avr/pgmspace.h>
27 //------------------------------------------------------------------------------
28 // callback function for date/time
29 void (*SdFile::dateTime_)(uint16_t* date, uint16_t* time) = NULL;
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;
40 // if first cluster of file link to directory entry
41 if (firstCluster_ == 0) {
42 firstCluster_ = curCluster_;
43 flags_ |= F_FILE_DIR_DIRTY;
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;
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;
58 // Increase directory file size by cluster size
59 fileSize_ += 512UL << vol_->clusterSizeShift_;
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_;
69 //------------------------------------------------------------------------------
71 * Close a file and force cached data and directory information
72 * to be written to the storage device.
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.
78 uint8_t SdFile::close(void) {
79 if (!sync())return false;
80 type_ = FAT_FILE_TYPE_CLOSED;
83 //------------------------------------------------------------------------------
85 * Check for contiguous file and return its raw block range.
87 * \param[out] bgnBlock the first block address for the file.
88 * \param[out] endBlock the last block address for the file.
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.
95 uint8_t SdFile::contiguousRange(uint32_t* bgnBlock, uint32_t* endBlock) {
97 if (firstCluster_ == 0) return false;
99 for (uint32_t c = firstCluster_; ; c++) {
101 if (!vol_->fatGet(c, &next)) return false;
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;
114 //------------------------------------------------------------------------------
116 * Create and open a new contiguous file of a specified size.
118 * \note This function only supports short DOS 8.3 names.
119 * See open() for more information.
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.
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.
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;
139 // calculate number of clusters needed
140 uint32_t count = ((size - 1) >> (vol_->clusterSizeShift_ + 9)) + 1;
143 if (!vol_->allocContiguous(count, &firstCluster_)) {
149 // insure sync() will update dir entry
150 flags_ |= F_FILE_DIR_DIRTY;
153 //------------------------------------------------------------------------------
155 * Return a files directory entry
157 * \param[out] dir Location for return of the files directory entry.
159 * \return The value one, true, is returned for success and
160 * the value zero, false, is returned for failure.
162 uint8_t SdFile::dirEntry(dir_t* dir) {
163 // make sure fields on SD are correct
164 if (!sync()) return false;
167 dir_t* p = cacheDirEntry(SdVolume::CACHE_FOR_READ);
168 if (!p) return false;
170 // copy to caller's struct
171 memcpy(dir, p, sizeof(dir_t));
174 //------------------------------------------------------------------------------
176 * Format the name field of \a dir into the 13 byte array
177 * \a name in standard 8.3 short name format.
179 * \param[in] dir The directory structure containing the name.
180 * \param[out] name A 13 byte char array for the formatted name.
182 void SdFile::dirName(const dir_t& dir, char* name) {
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];
191 //------------------------------------------------------------------------------
192 /** List directory contents to Serial.
194 * \param[in] flags The inclusive OR of
196 * LS_DATE - %Print file modification date
198 * LS_SIZE - %Print file size.
200 * LS_R - Recursive list of subdirectories.
202 * \param[in] indent Amount of space before file name. Used for recursive
203 * list to indicate subdirectory level.
205 void SdFile::ls(uint8_t flags, uint8_t indent) {
209 while ((p = readDirCache())) {
210 // done if past last used entry
211 if (p->name[0] == DIR_NAME_FREE) break;
213 // skip deleted entry and entries for . and ..
214 if (p->name[0] == DIR_NAME_DELETED || p->name[0] == '.') continue;
216 // only list subdirectories and files
217 if (!DIR_IS_FILE_OR_SUBDIR(p)) continue;
219 // print any indent spaces
220 for (int8_t i = 0; i < indent; i++) Serial.print(' ');
222 // print file name with possible blank fill
223 printDirName(*p, flags & (LS_DATE | LS_SIZE) ? 14 : 0);
225 // print modify date/time if requested
226 if (flags & LS_DATE) {
227 printFatDate(p->lastWriteDate);
229 printFatTime(p->lastWriteTime);
231 // print size if requested
232 if (!DIR_IS_SUBDIR(p) && (flags & LS_SIZE)) {
234 Serial.print(p->fileSize);
238 // list subdirectory content if requested
239 if ((flags & LS_R) && DIR_IS_SUBDIR(p)) {
240 uint16_t index = curPosition()/32 - 1;
242 if (s.open(this, index, O_READ)) s.ls(flags, indent + 2);
243 seekSet(32 * (index + 1));
247 //------------------------------------------------------------------------------
248 // format directory name field from a 8.3 name string
249 uint8_t SdFile::make83Name(const char* str, uint8_t* name) {
251 uint8_t n = 7; // max index for part before dot
253 // blank fill name and extension
254 while (i < 11) name[i++] = ' ';
256 while ((c = *str++) != '\0') {
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
262 // illegal FAT characters
263 PGM_P p = PSTR("|<>^+=?/[];,*\"\\");
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');
272 // must have a file name, extension is optional
273 return name[0] != ' ';
275 //------------------------------------------------------------------------------
276 /** Make a new directory.
278 * \param[in] dir An open SdFat instance for the directory that will containing
281 * \param[in] dirName A valid 8.3 DOS name for the new directory.
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.
288 uint8_t SdFile::makeDir(SdFile* dir, const char* dirName) {
291 // create a normal file
292 if (!open(dir, dirName, O_CREAT | O_EXCL | O_RDWR)) return false;
294 // convert SdFile to directory
296 type_ = FAT_FILE_TYPE_SUBDIR;
298 // allocate and zero first cluster
299 if (!addDirCluster())return false;
302 if (!sync()) return false;
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;
308 // change directory entry attribute
309 p->attributes = DIR_ATT_DIRECTORY;
311 // make entry for '.'
312 memcpy(&d, p, sizeof(d));
313 for (uint8_t i = 1; i < 11; i++) d.name[i] = ' ';
316 // cache block for '.' and '..'
317 uint32_t block = vol_->clusterStartBlock(firstCluster_);
318 if (!SdVolume::cacheRawBlock(block, SdVolume::CACHE_FOR_WRITE)) return false;
321 memcpy(&SdVolume::cacheBuffer_.dir[0], &d, sizeof(d));
323 // make entry for '..'
326 d.firstClusterLow = 0;
327 d.firstClusterHigh = 0;
329 d.firstClusterLow = dir->firstCluster_ & 0XFFFF;
330 d.firstClusterHigh = dir->firstCluster_ >> 16;
332 // copy '..' to block
333 memcpy(&SdVolume::cacheBuffer_.dir[1], &d, sizeof(d));
335 // set position after '..'
336 curPosition_ = 2 * sizeof(d);
339 return SdVolume::cacheFlush();
341 //------------------------------------------------------------------------------
343 * Open a file or directory by name.
345 * \param[in] dirFile An open SdFat instance for the directory containing the
348 * \param[in] fileName A valid 8.3 DOS name for a file to be opened.
350 * \param[in] oflag Values for \a oflag are constructed by a bitwise-inclusive
351 * OR of flags from the following list
353 * O_READ - Open for reading.
355 * O_RDONLY - Same as O_READ.
357 * O_WRITE - Open for writing.
359 * O_WRONLY - Same as O_WRITE.
361 * O_RDWR - Open for reading and writing.
363 * O_APPEND - If set, the file offset shall be set to the end of the
364 * file prior to each write.
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
369 * O_EXCL - If O_CREAT and O_EXCL are set, open() shall fail if the file exists.
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
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.
379 * \note Directory files must be opened read only. Write and truncation is
380 * not allowed for directory files.
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.
388 uint8_t SdFile::open(SdFile* dirFile, const char* fileName, uint8_t oflag) {
392 // error if already open
393 if (isOpen())return false;
395 if (!make83Name(fileName, dname)) return false;
396 vol_ = dirFile->vol_;
399 // bool for empty entry found
400 uint8_t emptyFound = false;
403 while (dirFile->curPosition_ < dirFile->fileSize_) {
404 uint8_t index = 0XF & (dirFile->curPosition_ >> 5);
405 p = dirFile->readDirCache();
406 if (p == NULL) return false;
408 if (p->name[0] == DIR_NAME_FREE || p->name[0] == DIR_NAME_DELETED) {
409 // remember first empty slot
413 dirBlock_ = SdVolume::cacheBlockNumber_;
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;
422 return openCachedEntry(0XF & index, oflag);
425 // only create file if O_CREAT and O_WRITE
426 if ((oflag & (O_CREAT | O_WRITE)) != (O_CREAT | O_WRITE)) return false;
428 // cache found slot or add cluster if end of file
430 p = cacheDirEntry(SdVolume::CACHE_FOR_WRITE);
431 if (!p) return false;
433 if (dirFile->type_ == FAT_FILE_TYPE_ROOT16) return false;
435 // add and zero cluster for dirFile - first cluster is in cache for write
436 if (!dirFile->addDirCluster()) return false;
438 // use first entry in cluster
440 p = SdVolume::cacheBuffer_.dir;
442 // initialize as empty file
443 memset(p, 0, sizeof(dir_t));
444 memcpy(p->name, dname, 11);
448 // call user function
449 dateTime_(&p->creationDate, &p->creationTime);
451 // use default date/time
452 p->creationDate = FAT_DEFAULT_DATE;
453 p->creationTime = FAT_DEFAULT_TIME;
455 p->lastAccessDate = p->creationDate;
456 p->lastWriteDate = p->creationDate;
457 p->lastWriteTime = p->creationTime;
459 // force write of entry to SD
460 if (!SdVolume::cacheFlush()) return false;
462 // open entry in cache
463 return openCachedEntry(dirIndex_, oflag);
465 //------------------------------------------------------------------------------
467 * Open a file by index.
469 * \param[in] dirFile An open SdFat instance for the directory.
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.
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.
477 * See open() by fileName for definition of flags and return values.
480 uint8_t SdFile::open(SdFile* dirFile, uint16_t index, uint8_t oflag) {
481 // error if already open
482 if (isOpen())return false;
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;
487 vol_ = dirFile->vol_;
489 // seek to location of entry
490 if (!dirFile->seekSet(32 * index)) return false;
492 // read entry into cache
493 dir_t* p = dirFile->readDirCache();
494 if (p == NULL) return false;
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] == '.') {
502 return openCachedEntry(index & 0XF, oflag);
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;
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;
514 // remember location of directory entry on SD
515 dirIndex_ = dirIndex;
516 dirBlock_ = SdVolume::cacheBlockNumber_;
518 // copy first cluster number for directory fields
519 firstCluster_ = (uint32_t)p->firstClusterHigh << 16;
520 firstCluster_ |= p->firstClusterLow;
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;
532 // save open flags for read/write
533 flags_ = oflag & (O_ACCMODE | O_SYNC | O_APPEND);
535 // set to start of file
539 // truncate file to zero length if requested
540 if (oflag & O_TRUNC) return truncate(0);
543 //------------------------------------------------------------------------------
545 * Open a volume's root directory.
547 * \param[in] vol The FAT volume containing the root directory to be opened.
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.
554 uint8_t SdFile::openRoot(SdVolume* vol) {
555 // error if file is already open
556 if (isOpen()) return false;
558 if (vol->fatType() == 16) {
559 type_ = FAT_FILE_TYPE_ROOT16;
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;
567 // volume is not initialized or FAT12
574 // set to start of file
578 // root has no directory entry
583 //------------------------------------------------------------------------------
584 /** %Print the name field of a directory entry in 8.3 format to Serial.
586 * \param[in] dir The directory structure containing the name.
587 * \param[in] width Blank fill name if length is less than \a width.
589 void SdFile::printDirName(const dir_t& dir, uint8_t width) {
591 for (uint8_t i = 0; i < 11; i++) {
592 if (dir.name[i] == ' ')continue;
598 Serial.write(dir.name[i]);
600 Serial.print(dir.name[i]);
604 if (DIR_IS_SUBDIR(&dir)) {
613 //------------------------------------------------------------------------------
614 /** %Print a directory date field to Serial.
616 * Format is yyyy-mm-dd.
618 * \param[in] fatDate The date field from a directory entry.
620 void SdFile::printFatDate(uint16_t fatDate) {
621 Serial.print(FAT_YEAR(fatDate));
623 printTwoDigits(FAT_MONTH(fatDate));
625 printTwoDigits(FAT_DAY(fatDate));
627 //------------------------------------------------------------------------------
628 /** %Print a directory time field to Serial.
630 * Format is hh:mm:ss.
632 * \param[in] fatTime The time field from a directory entry.
634 void SdFile::printFatTime(uint16_t fatTime) {
635 printTwoDigits(FAT_HOUR(fatTime));
637 printTwoDigits(FAT_MINUTE(fatTime));
639 printTwoDigits(FAT_SECOND(fatTime));
641 //------------------------------------------------------------------------------
642 /** %Print a value as two digits to Serial.
644 * \param[in] v Value to be printed, 0 <= \a v <= 99
646 void SdFile::printTwoDigits(uint8_t v) {
649 str[1] = '0' + v % 10;
653 //------------------------------------------------------------------------------
655 * Read data from a file starting at the current position.
657 * \param[out] buf Pointer to the location that will receive the data.
659 * \param[in] nbyte Maximum number of bytes to read.
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.
668 int16_t SdFile::read(void* buf, uint16_t nbyte) {
669 uint8_t* dst = reinterpret_cast<uint8_t*>(buf);
671 // error if not open or write only
672 if (!isOpen() || !(flags_ & O_READ)) return -1;
674 // max bytes left in file
675 if (nbyte > (fileSize_ - curPosition_)) nbyte = fileSize_ - curPosition_;
677 // amount left to read
678 uint16_t toRead = nbyte;
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);
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_;
692 // get next cluster from FAT
693 if (!vol_->fatGet(curCluster_, &curCluster_)) return -1;
696 block = vol_->clusterStartBlock(curCluster_) + blockOfCluster;
700 // amount to be read from current block
701 if (n > (512 - offset)) n = 512 - offset;
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;
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++;
720 //------------------------------------------------------------------------------
722 * Read the next directory entry from a directory file.
724 * \param[out] dir The dir_t struct that will receive the data.
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.
732 int8_t SdFile::readDir(dir_t* dir) {
734 // if not a directory file or miss-positioned return an error
735 if (!isDir() || (0X1F & curPosition_)) return -1;
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;
745 // error, end of file, or past last entry
746 return n < 0 ? -1 : 0;
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;
755 // index of entry in cache
756 uint8_t i = (curPosition_ >> 5) & 0XF;
758 // use read to locate and cache block
759 if (read() < 0) return NULL;
761 // advance to next entry
764 // return pointer to entry
765 return (SdVolume::cacheBuffer_.dir + i);
767 //------------------------------------------------------------------------------
771 * The directory entry and all data for the file are deleted.
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".
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.
782 uint8_t SdFile::remove(void) {
783 // free any clusters - will fail if read-only or directory
784 if (!truncate(0)) return false;
786 // cache directory entry
787 dir_t* d = cacheDirEntry(SdVolume::CACHE_FOR_WRITE);
788 if (!d) return false;
790 // mark entry deleted
791 d->name[0] = DIR_NAME_DELETED;
793 // set this SdFile closed
794 type_ = FAT_FILE_TYPE_CLOSED;
797 return SdVolume::cacheFlush();
799 //------------------------------------------------------------------------------
803 * The directory entry and all data for the file are deleted.
805 * \param[in] dirFile The directory that contains the file.
806 * \param[in] fileName The name of the file to be removed.
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".
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.
818 uint8_t SdFile::remove(SdFile* dirFile, const char* fileName) {
820 if (!file.open(dirFile, fileName, O_WRITE)) return false;
821 return file.remove();
823 //------------------------------------------------------------------------------
824 /** Remove a directory file.
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.
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".
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.
839 uint8_t SdFile::rmDir(void) {
840 // must be open subdirectory
841 if (!isSubDir()) return false;
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;
854 if (DIR_IS_FILE_OR_SUBDIR(p)) return false;
856 // convert empty directory to normal file for remove
857 type_ = FAT_FILE_TYPE_NORMAL;
861 //------------------------------------------------------------------------------
862 /** Recursively delete a directory and all contained files.
864 * This is like the Unix/Linux 'rm -rf *' if called with the root directory
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.
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().
874 * \return The value one, true, is returned for success and
875 * the value zero, false, is returned for failure.
877 uint8_t SdFile::rmRfStar(void) {
879 while (curPosition_ < fileSize_) {
883 uint16_t index = curPosition_/32;
885 dir_t* p = readDirCache();
886 if (!p) return false;
888 // done if past last entry
889 if (p->name[0] == DIR_NAME_FREE) break;
891 // skip empty slot or '.' or '..'
892 if (p->name[0] == DIR_NAME_DELETED || p->name[0] == '.') continue;
894 // skip if part of long file name or volume label in root
895 if (!DIR_IS_FILE_OR_SUBDIR(p)) continue;
897 if (!f.open(this, index, O_READ)) return false;
899 // recursively delete
900 if (!f.rmRfStar()) return false;
904 if (!f.remove()) return false;
906 // position to next entry if required
907 if (curPosition_ != (32*(index + 1))) {
908 if (!seekSet(32*(index + 1))) return false;
911 // don't try to delete root
912 if (isRoot()) return true;
915 //------------------------------------------------------------------------------
917 * Sets a file's position.
919 * \param[in] pos The new position in bytes from the beginning of the file.
921 * \return The value one, true, is returned for success and
922 * the value zero, false, is returned for failure.
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;
928 if (type_ == FAT_FILE_TYPE_ROOT16) {
933 // set position to start of file
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);
942 if (nNew < nCur || curPosition_ == 0) {
943 // must follow chain from first cluster
944 curCluster_ = firstCluster_;
946 // advance from curPosition
950 if (!vol_->fatGet(curCluster_, &curCluster_)) return false;
955 //------------------------------------------------------------------------------
957 * The sync() call causes all modified data and directory fields
958 * to be written to the storage device.
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.
965 uint8_t SdFile::sync(void) {
966 // only allow open files and directories
967 if (!isOpen()) return false;
969 if (flags_ & F_FILE_DIR_DIRTY) {
970 dir_t* d = cacheDirEntry(SdVolume::CACHE_FOR_WRITE);
971 if (!d) return false;
973 // do not set filesize for dir files
974 if (!isDir()) d->fileSize = fileSize_;
976 // update first cluster fields
977 d->firstClusterLow = firstCluster_ & 0XFFFF;
978 d->firstClusterHigh = firstCluster_ >> 16;
980 // set modify time if user supplied a callback date/time function
982 dateTime_(&d->lastWriteDate, &d->lastWriteTime);
983 d->lastAccessDate = d->lastWriteDate;
985 // clear directory dirty
986 flags_ &= ~F_FILE_DIR_DIRTY;
988 return SdVolume::cacheFlush();
990 //------------------------------------------------------------------------------
992 * Set a file's timestamps in its directory entry.
994 * \param[in] flags Values for \a flags are constructed by a bitwise-inclusive
995 * OR of flags from the following list
997 * T_ACCESS - Set the file's last access date.
999 * T_CREATE - Set the file's creation date and time.
1001 * T_WRITE - Set the file's last write/modification date and time.
1003 * \param[in] year Valid range 1980 - 2107 inclusive.
1005 * \param[in] month Valid range 1 - 12 inclusive.
1007 * \param[in] day Valid range 1 - 31 inclusive.
1009 * \param[in] hour Valid range 0 - 23 inclusive.
1011 * \param[in] minute Valid range 0 - 59 inclusive.
1013 * \param[in] second Valid range 0 - 59 inclusive
1015 * \note It is possible to set an invalid date since there is no check for
1016 * the number of days in a month.
1019 * Modify and access timestamps may be overwritten if a date time callback
1020 * function has been set by dateTimeCallback().
1022 * \return The value one, true, is returned for success and
1023 * the value zero, false, is returned for failure.
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) {
1039 dir_t* d = cacheDirEntry(SdVolume::CACHE_FOR_WRITE);
1040 if (!d) return false;
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;
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;
1053 if (flags & T_WRITE) {
1054 d->lastWriteDate = dirDate;
1055 d->lastWriteTime = dirTime;
1057 SdVolume::cacheSetDirty();
1060 //------------------------------------------------------------------------------
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.
1066 * \param[in] length The desired length for the file.
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.
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;
1077 // error if length is greater than current size
1078 if (length > fileSize_) return false;
1080 // fileSize and length are zero - nothing to do
1081 if (fileSize_ == 0) return true;
1083 // remember position for seek after truncation
1084 uint32_t newPos = curPosition_ > length ? length : curPosition_;
1086 // position to last cluster in truncated file
1087 if (!seekSet(length)) return false;
1090 // free all clusters
1091 if (!vol_->freeChain(firstCluster_)) return false;
1095 if (!vol_->fatGet(curCluster_, &toFree)) return false;
1097 if (!vol_->isEOC(toFree)) {
1098 // free extra clusters
1099 if (!vol_->freeChain(toFree)) return false;
1101 // current cluster is end of chain
1102 if (!vol_->fatPutEOC(curCluster_)) return false;
1107 // need to update directory entry
1108 flags_ |= F_FILE_DIR_DIRTY;
1110 if (!sync()) return false;
1112 // set file to correct position
1113 return seekSet(newPos);
1115 //------------------------------------------------------------------------------
1117 * Write data to an open file.
1119 * \note Data is moved to the cache but may not be written to the
1120 * storage device until sync() is called.
1122 * \param[in] buf Pointer to the location of the data to be written.
1124 * \param[in] nbyte Number of bytes to write.
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.
1133 size_t SdFile::write(const void* buf, uint16_t nbyte) {
1135 int16_t SdFile::write(const void* buf, uint16_t nbyte) {
1137 // convert void* to uint8_t* - must be before goto statements
1138 const uint8_t* src = reinterpret_cast<const uint8_t*>(buf);
1140 // number of bytes left to write - must be before goto statements
1141 uint16_t nToWrite = nbyte;
1143 // error if not a normal file or is read-only
1144 if (!isFile() || !(flags_ & O_WRITE)) goto writeErrorReturn;
1146 // seek to end of file if append flag
1147 if ((flags_ & O_APPEND) && curPosition_ != fileSize_) {
1148 if (!seekEnd()) goto writeErrorReturn;
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;
1161 curCluster_ = firstCluster_;
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;
1174 // max space in block
1175 uint16_t n = 512 - blockOffset;
1177 // lesser of space and amount to write
1178 if (n > nToWrite) n = nToWrite;
1180 // block for data write
1181 uint32_t block = vol_->clusterStartBlock(curCluster_) + blockOfCluster;
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;
1188 if (!vol_->writeBlock(block, src)) goto writeErrorReturn;
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();
1197 // rewrite part of block
1198 if (!SdVolume::cacheRawBlock(block, SdVolume::CACHE_FOR_WRITE)) {
1199 goto writeErrorReturn;
1202 uint8_t* dst = SdVolume::cacheBuffer_.data + blockOffset;
1203 uint8_t* end = dst + n;
1204 while (dst != end) *dst++ = *src++;
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;
1218 if (flags_ & O_SYNC) {
1219 if (!sync()) goto writeErrorReturn;
1224 // return for write error
1228 //------------------------------------------------------------------------------
1230 * Write a byte to a file. Required by the Arduino Print class.
1232 * Use SdFile::writeError to check for errors.
1235 size_t SdFile::write(uint8_t b) {
1236 return write(&b, 1);
1239 void SdFile::write(uint8_t b) {
1243 //------------------------------------------------------------------------------
1245 * Write a string to a file. Used by the Arduino Print class.
1247 * Use SdFile::writeError to check for errors.
1250 size_t SdFile::write(const char* str) {
1251 return write(str, strlen(str));
1254 void SdFile::write(const char* str) {
1255 write(str, strlen(str));
1258 //------------------------------------------------------------------------------
1260 * Write a PROGMEM string to a file.
1262 * Use SdFile::writeError to check for errors.
1264 void SdFile::write_P(PGM_P str) {
1265 for (uint8_t c; (c = pgm_read_byte(str)); str++) write(c);
1267 //------------------------------------------------------------------------------
1269 * Write a PROGMEM string followed by CR/LF to a file.
1271 * Use SdFile::writeError to check for errors.
1273 void SdFile::writeln_P(PGM_P str) {