PlatformIO package of the Teensy core framework compatible with GCC 10 & C++20
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

1253 lines
41KB

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