Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

1254 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. int16_t SdFile::read(void* buf, uint16_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. uint16_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. uint16_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) &&
  638. block != SdVolume::cacheBlockNumber_) {
  639. if (!vol_->readData(block, offset, n, dst)) return -1;
  640. dst += n;
  641. } else {
  642. // read block to cache and copy data to caller
  643. if (!SdVolume::cacheRawBlock(block, SdVolume::CACHE_FOR_READ)) return -1;
  644. uint8_t* src = SdVolume::cacheBuffer_.data + offset;
  645. uint8_t* end = src + n;
  646. while (src != end) *dst++ = *src++;
  647. }
  648. curPosition_ += n;
  649. toRead -= n;
  650. }
  651. return nbyte;
  652. }
  653. //------------------------------------------------------------------------------
  654. /**
  655. * Read the next directory entry from a directory file.
  656. *
  657. * \param[out] dir The dir_t struct that will receive the data.
  658. *
  659. * \return For success readDir() returns the number of bytes read.
  660. * A value of zero will be returned if end of file is reached.
  661. * If an error occurs, readDir() returns -1. Possible errors include
  662. * readDir() called before a directory has been opened, this is not
  663. * a directory file or an I/O error occurred.
  664. */
  665. int8_t SdFile::readDir(dir_t* dir) {
  666. int8_t n;
  667. // if not a directory file or miss-positioned return an error
  668. if (!isDir() || (0X1F & curPosition_)) return -1;
  669. while ((n = read(dir, sizeof(dir_t))) == sizeof(dir_t)) {
  670. // last entry if DIR_NAME_FREE
  671. if (dir->name[0] == DIR_NAME_FREE) break;
  672. // skip empty entries and entry for . and ..
  673. if (dir->name[0] == DIR_NAME_DELETED || dir->name[0] == '.') continue;
  674. // return if normal file or subdirectory
  675. if (DIR_IS_FILE_OR_SUBDIR(dir)) return n;
  676. }
  677. // error, end of file, or past last entry
  678. return n < 0 ? -1 : 0;
  679. }
  680. //------------------------------------------------------------------------------
  681. // Read next directory entry into the cache
  682. // Assumes file is correctly positioned
  683. dir_t* SdFile::readDirCache(void) {
  684. // error if not directory
  685. if (!isDir()) return NULL;
  686. // index of entry in cache
  687. uint8_t i = (curPosition_ >> 5) & 0XF;
  688. // use read to locate and cache block
  689. if (read() < 0) return NULL;
  690. // advance to next entry
  691. curPosition_ += 31;
  692. // return pointer to entry
  693. return (SdVolume::cacheBuffer_.dir + i);
  694. }
  695. //------------------------------------------------------------------------------
  696. /**
  697. * Remove a file.
  698. *
  699. * The directory entry and all data for the file are deleted.
  700. *
  701. * \note This function should not be used to delete the 8.3 version of a
  702. * file that has a long name. For example if a file has the long name
  703. * "New Text Document.txt" you should not delete the 8.3 name "NEWTEX~1.TXT".
  704. *
  705. * \return The value one, true, is returned for success and
  706. * the value zero, false, is returned for failure.
  707. * Reasons for failure include the file read-only, is a directory,
  708. * or an I/O error occurred.
  709. */
  710. uint8_t SdFile::remove(void) {
  711. // free any clusters - will fail if read-only or directory
  712. if (!truncate(0)) return false;
  713. // cache directory entry
  714. dir_t* d = cacheDirEntry(SdVolume::CACHE_FOR_WRITE);
  715. if (!d) return false;
  716. // mark entry deleted
  717. d->name[0] = DIR_NAME_DELETED;
  718. // set this SdFile closed
  719. type_ = FAT_FILE_TYPE_CLOSED;
  720. // write entry to SD
  721. return SdVolume::cacheFlush();
  722. }
  723. //------------------------------------------------------------------------------
  724. /**
  725. * Remove a file.
  726. *
  727. * The directory entry and all data for the file are deleted.
  728. *
  729. * \param[in] dirFile The directory that contains the file.
  730. * \param[in] fileName The name of the file to be removed.
  731. *
  732. * \note This function should not be used to delete the 8.3 version of a
  733. * file that has a long name. For example if a file has the long name
  734. * "New Text Document.txt" you should not delete the 8.3 name "NEWTEX~1.TXT".
  735. *
  736. * \return The value one, true, is returned for success and
  737. * the value zero, false, is returned for failure.
  738. * Reasons for failure include the file is a directory, is read only,
  739. * \a dirFile is not a directory, \a fileName is not found
  740. * or an I/O error occurred.
  741. */
  742. uint8_t SdFile::remove(SdFile* dirFile, const char* fileName) {
  743. SdFile file;
  744. if (!file.open(dirFile, fileName, O_WRITE)) return false;
  745. return file.remove();
  746. }
  747. //------------------------------------------------------------------------------
  748. /** Remove a directory file.
  749. *
  750. * The directory file will be removed only if it is empty and is not the
  751. * root directory. rmDir() follows DOS and Windows and ignores the
  752. * read-only attribute for the directory.
  753. *
  754. * \note This function should not be used to delete the 8.3 version of a
  755. * directory that has a long name. For example if a directory has the
  756. * long name "New folder" you should not delete the 8.3 name "NEWFOL~1".
  757. *
  758. * \return The value one, true, is returned for success and
  759. * the value zero, false, is returned for failure.
  760. * Reasons for failure include the file is not a directory, is the root
  761. * directory, is not empty, or an I/O error occurred.
  762. */
  763. uint8_t SdFile::rmDir(void) {
  764. // must be open subdirectory
  765. if (!isSubDir()) return false;
  766. rewind();
  767. // make sure directory is empty
  768. while (curPosition_ < fileSize_) {
  769. dir_t* p = readDirCache();
  770. if (p == NULL) return false;
  771. // done if past last used entry
  772. if (p->name[0] == DIR_NAME_FREE) break;
  773. // skip empty slot or '.' or '..'
  774. if (p->name[0] == DIR_NAME_DELETED || p->name[0] == '.') continue;
  775. // error not empty
  776. if (DIR_IS_FILE_OR_SUBDIR(p)) return false;
  777. }
  778. // convert empty directory to normal file for remove
  779. type_ = FAT_FILE_TYPE_NORMAL;
  780. flags_ |= O_WRITE;
  781. return remove();
  782. }
  783. //------------------------------------------------------------------------------
  784. /** Recursively delete a directory and all contained files.
  785. *
  786. * This is like the Unix/Linux 'rm -rf *' if called with the root directory
  787. * hence the name.
  788. *
  789. * Warning - This will remove all contents of the directory including
  790. * subdirectories. The directory will then be removed if it is not root.
  791. * The read-only attribute for files will be ignored.
  792. *
  793. * \note This function should not be used to delete the 8.3 version of
  794. * a directory that has a long name. See remove() and rmDir().
  795. *
  796. * \return The value one, true, is returned for success and
  797. * the value zero, false, is returned for failure.
  798. */
  799. uint8_t SdFile::rmRfStar(void) {
  800. rewind();
  801. while (curPosition_ < fileSize_) {
  802. SdFile f;
  803. // remember position
  804. uint16_t index = curPosition_/32;
  805. dir_t* p = readDirCache();
  806. if (!p) return false;
  807. // done if past last entry
  808. if (p->name[0] == DIR_NAME_FREE) break;
  809. // skip empty slot or '.' or '..'
  810. if (p->name[0] == DIR_NAME_DELETED || p->name[0] == '.') continue;
  811. // skip if part of long file name or volume label in root
  812. if (!DIR_IS_FILE_OR_SUBDIR(p)) continue;
  813. if (!f.open(this, index, O_READ)) return false;
  814. if (f.isSubDir()) {
  815. // recursively delete
  816. if (!f.rmRfStar()) return false;
  817. } else {
  818. // ignore read-only
  819. f.flags_ |= O_WRITE;
  820. if (!f.remove()) return false;
  821. }
  822. // position to next entry if required
  823. if (curPosition_ != (uint32_t)(32*(index + 1))) {
  824. if (!seekSet(32*(index + 1))) return false;
  825. }
  826. }
  827. // don't try to delete root
  828. if (isRoot()) return true;
  829. return rmDir();
  830. }
  831. //------------------------------------------------------------------------------
  832. /**
  833. * Sets a file's position.
  834. *
  835. * \param[in] pos The new position in bytes from the beginning of the file.
  836. *
  837. * \return The value one, true, is returned for success and
  838. * the value zero, false, is returned for failure.
  839. */
  840. uint8_t SdFile::seekSet(uint32_t pos) {
  841. // error if file not open or seek past end of file
  842. if (!isOpen() || pos > fileSize_) return false;
  843. if (type_ == FAT_FILE_TYPE_ROOT16) {
  844. curPosition_ = pos;
  845. return true;
  846. }
  847. if (pos == 0) {
  848. // set position to start of file
  849. curCluster_ = 0;
  850. curPosition_ = 0;
  851. return true;
  852. }
  853. // calculate cluster index for cur and new position
  854. uint32_t nCur = (curPosition_ - 1) >> (vol_->clusterSizeShift_ + 9);
  855. uint32_t nNew = (pos - 1) >> (vol_->clusterSizeShift_ + 9);
  856. if (nNew < nCur || curPosition_ == 0) {
  857. // must follow chain from first cluster
  858. curCluster_ = firstCluster_;
  859. } else {
  860. // advance from curPosition
  861. nNew -= nCur;
  862. }
  863. while (nNew--) {
  864. if (!vol_->fatGet(curCluster_, &curCluster_)) return false;
  865. }
  866. curPosition_ = pos;
  867. return true;
  868. }
  869. //------------------------------------------------------------------------------
  870. /**
  871. * The sync() call causes all modified data and directory fields
  872. * to be written to the storage device.
  873. *
  874. * \return The value one, true, is returned for success and
  875. * the value zero, false, is returned for failure.
  876. * Reasons for failure include a call to sync() before a file has been
  877. * opened or an I/O error.
  878. */
  879. uint8_t SdFile::sync(void) {
  880. // only allow open files and directories
  881. if (!isOpen()) return false;
  882. if (flags_ & F_FILE_DIR_DIRTY) {
  883. dir_t* d = cacheDirEntry(SdVolume::CACHE_FOR_WRITE);
  884. if (!d) return false;
  885. // do not set filesize for dir files
  886. if (!isDir()) d->fileSize = fileSize_;
  887. // update first cluster fields
  888. d->firstClusterLow = firstCluster_ & 0XFFFF;
  889. d->firstClusterHigh = firstCluster_ >> 16;
  890. // set modify time if user supplied a callback date/time function
  891. if (dateTime_) {
  892. dateTime_(&d->lastWriteDate, &d->lastWriteTime);
  893. d->lastAccessDate = d->lastWriteDate;
  894. }
  895. // clear directory dirty
  896. flags_ &= ~F_FILE_DIR_DIRTY;
  897. }
  898. return SdVolume::cacheFlush();
  899. }
  900. //------------------------------------------------------------------------------
  901. /**
  902. * Set a file's timestamps in its directory entry.
  903. *
  904. * \param[in] flags Values for \a flags are constructed by a bitwise-inclusive
  905. * OR of flags from the following list
  906. *
  907. * T_ACCESS - Set the file's last access date.
  908. *
  909. * T_CREATE - Set the file's creation date and time.
  910. *
  911. * T_WRITE - Set the file's last write/modification date and time.
  912. *
  913. * \param[in] year Valid range 1980 - 2107 inclusive.
  914. *
  915. * \param[in] month Valid range 1 - 12 inclusive.
  916. *
  917. * \param[in] day Valid range 1 - 31 inclusive.
  918. *
  919. * \param[in] hour Valid range 0 - 23 inclusive.
  920. *
  921. * \param[in] minute Valid range 0 - 59 inclusive.
  922. *
  923. * \param[in] second Valid range 0 - 59 inclusive
  924. *
  925. * \note It is possible to set an invalid date since there is no check for
  926. * the number of days in a month.
  927. *
  928. * \note
  929. * Modify and access timestamps may be overwritten if a date time callback
  930. * function has been set by dateTimeCallback().
  931. *
  932. * \return The value one, true, is returned for success and
  933. * the value zero, false, is returned for failure.
  934. */
  935. uint8_t SdFile::timestamp(uint8_t flags, uint16_t year, uint8_t month,
  936. uint8_t day, uint8_t hour, uint8_t minute, uint8_t second) {
  937. if (!isOpen()
  938. || year < 1980
  939. || year > 2107
  940. || month < 1
  941. || month > 12
  942. || day < 1
  943. || day > 31
  944. || hour > 23
  945. || minute > 59
  946. || second > 59) {
  947. return false;
  948. }
  949. dir_t* d = cacheDirEntry(SdVolume::CACHE_FOR_WRITE);
  950. if (!d) return false;
  951. uint16_t dirDate = FAT_DATE(year, month, day);
  952. uint16_t dirTime = FAT_TIME(hour, minute, second);
  953. if (flags & T_ACCESS) {
  954. d->lastAccessDate = dirDate;
  955. }
  956. if (flags & T_CREATE) {
  957. d->creationDate = dirDate;
  958. d->creationTime = dirTime;
  959. // seems to be units of 1/100 second not 1/10 as Microsoft states
  960. d->creationTimeTenths = second & 1 ? 100 : 0;
  961. }
  962. if (flags & T_WRITE) {
  963. d->lastWriteDate = dirDate;
  964. d->lastWriteTime = dirTime;
  965. }
  966. SdVolume::cacheSetDirty();
  967. return sync();
  968. }
  969. //------------------------------------------------------------------------------
  970. /**
  971. * Truncate a file to a specified length. The current file position
  972. * will be maintained if it is less than or equal to \a length otherwise
  973. * it will be set to end of file.
  974. *
  975. * \param[in] length The desired length for the file.
  976. *
  977. * \return The value one, true, is returned for success and
  978. * the value zero, false, is returned for failure.
  979. * Reasons for failure include file is read only, file is a directory,
  980. * \a length is greater than the current file size or an I/O error occurs.
  981. */
  982. uint8_t SdFile::truncate(uint32_t length) {
  983. // error if not a normal file or read-only
  984. if (!isFile() || !(flags_ & O_WRITE)) return false;
  985. // error if length is greater than current size
  986. if (length > fileSize_) return false;
  987. // fileSize and length are zero - nothing to do
  988. if (fileSize_ == 0) return true;
  989. // remember position for seek after truncation
  990. uint32_t newPos = curPosition_ > length ? length : curPosition_;
  991. // position to last cluster in truncated file
  992. if (!seekSet(length)) return false;
  993. if (length == 0) {
  994. // free all clusters
  995. if (!vol_->freeChain(firstCluster_)) return false;
  996. firstCluster_ = 0;
  997. } else {
  998. uint32_t toFree;
  999. if (!vol_->fatGet(curCluster_, &toFree)) return false;
  1000. if (!vol_->isEOC(toFree)) {
  1001. // free extra clusters
  1002. if (!vol_->freeChain(toFree)) return false;
  1003. // current cluster is end of chain
  1004. if (!vol_->fatPutEOC(curCluster_)) return false;
  1005. }
  1006. }
  1007. fileSize_ = length;
  1008. // need to update directory entry
  1009. flags_ |= F_FILE_DIR_DIRTY;
  1010. if (!sync()) return false;
  1011. // set file to correct position
  1012. return seekSet(newPos);
  1013. }
  1014. //------------------------------------------------------------------------------
  1015. /**
  1016. * Write data to an open file.
  1017. *
  1018. * \note Data is moved to the cache but may not be written to the
  1019. * storage device until sync() is called.
  1020. *
  1021. * \param[in] buf Pointer to the location of the data to be written.
  1022. *
  1023. * \param[in] nbyte Number of bytes to write.
  1024. *
  1025. * \return For success write() returns the number of bytes written, always
  1026. * \a nbyte. If an error occurs, write() returns -1. Possible errors
  1027. * include write() is called before a file has been opened, write is called
  1028. * for a read-only file, device is full, a corrupt file system or an I/O error.
  1029. *
  1030. */
  1031. size_t SdFile::write(const void* buf, uint16_t nbyte) {
  1032. // convert void* to uint8_t* - must be before goto statements
  1033. const uint8_t* src = reinterpret_cast<const uint8_t*>(buf);
  1034. // number of bytes left to write - must be before goto statements
  1035. uint16_t nToWrite = nbyte;
  1036. // error if not a normal file or is read-only
  1037. if (!isFile() || !(flags_ & O_WRITE)) goto writeErrorReturn;
  1038. // seek to end of file if append flag
  1039. if ((flags_ & O_APPEND) && curPosition_ != fileSize_) {
  1040. if (!seekEnd()) goto writeErrorReturn;
  1041. }
  1042. while (nToWrite > 0) {
  1043. uint8_t blockOfCluster = vol_->blockOfCluster(curPosition_);
  1044. uint16_t blockOffset = curPosition_ & 0X1FF;
  1045. if (blockOfCluster == 0 && blockOffset == 0) {
  1046. // start of new cluster
  1047. if (curCluster_ == 0) {
  1048. if (firstCluster_ == 0) {
  1049. // allocate first cluster of file
  1050. if (!addCluster()) goto writeErrorReturn;
  1051. } else {
  1052. curCluster_ = firstCluster_;
  1053. }
  1054. } else {
  1055. uint32_t next;
  1056. if (!vol_->fatGet(curCluster_, &next)) return false;
  1057. if (vol_->isEOC(next)) {
  1058. // add cluster if at end of chain
  1059. if (!addCluster()) goto writeErrorReturn;
  1060. } else {
  1061. curCluster_ = next;
  1062. }
  1063. }
  1064. }
  1065. // max space in block
  1066. uint16_t n = 512 - blockOffset;
  1067. // lesser of space and amount to write
  1068. if (n > nToWrite) n = nToWrite;
  1069. // block for data write
  1070. uint32_t block = vol_->clusterStartBlock(curCluster_) + blockOfCluster;
  1071. if (n == 512) {
  1072. // full block - don't need to use cache
  1073. // invalidate cache if block is in cache
  1074. if (SdVolume::cacheBlockNumber_ == block) {
  1075. SdVolume::cacheBlockNumber_ = 0XFFFFFFFF;
  1076. }
  1077. if (!vol_->writeBlock(block, src)) goto writeErrorReturn;
  1078. src += 512;
  1079. } else {
  1080. if (blockOffset == 0 && curPosition_ >= fileSize_) {
  1081. // start of new block don't need to read into cache
  1082. if (!SdVolume::cacheFlush()) goto writeErrorReturn;
  1083. SdVolume::cacheBlockNumber_ = block;
  1084. SdVolume::cacheSetDirty();
  1085. } else {
  1086. // rewrite part of block
  1087. if (!SdVolume::cacheRawBlock(block, SdVolume::CACHE_FOR_WRITE)) {
  1088. goto writeErrorReturn;
  1089. }
  1090. }
  1091. uint8_t* dst = SdVolume::cacheBuffer_.data + blockOffset;
  1092. uint8_t* end = dst + n;
  1093. while (dst != end) *dst++ = *src++;
  1094. }
  1095. nToWrite -= n;
  1096. curPosition_ += n;
  1097. }
  1098. if (curPosition_ > fileSize_) {
  1099. // update fileSize and insure sync will update dir entry
  1100. fileSize_ = curPosition_;
  1101. flags_ |= F_FILE_DIR_DIRTY;
  1102. } else if (dateTime_ && nbyte) {
  1103. // insure sync will update modified date and time
  1104. flags_ |= F_FILE_DIR_DIRTY;
  1105. }
  1106. if (flags_ & O_SYNC) {
  1107. if (!sync()) goto writeErrorReturn;
  1108. }
  1109. return nbyte;
  1110. writeErrorReturn:
  1111. // return for write error
  1112. //writeError = true;
  1113. setWriteError();
  1114. return 0;
  1115. }
  1116. //------------------------------------------------------------------------------
  1117. /**
  1118. * Write a byte to a file. Required by the Arduino Print class.
  1119. *
  1120. * Use SdFile::writeError to check for errors.
  1121. */
  1122. size_t SdFile::write(uint8_t b) {
  1123. return write(&b, 1);
  1124. }
  1125. //------------------------------------------------------------------------------
  1126. /**
  1127. * Write a string to a file. Used by the Arduino Print class.
  1128. *
  1129. * Use SdFile::writeError to check for errors.
  1130. */
  1131. size_t SdFile::write(const char* str) {
  1132. return write(str, strlen(str));
  1133. }
  1134. //------------------------------------------------------------------------------
  1135. /**
  1136. * Write a PROGMEM string to a file.
  1137. *
  1138. * Use SdFile::writeError to check for errors.
  1139. */
  1140. void SdFile::write_P(PGM_P str) {
  1141. for (uint8_t c; (c = pgm_read_byte(str)); str++) write(c);
  1142. }
  1143. //------------------------------------------------------------------------------
  1144. /**
  1145. * Write a PROGMEM string followed by CR/LF to a file.
  1146. *
  1147. * Use SdFile::writeError to check for errors.
  1148. */
  1149. void SdFile::writeln_P(PGM_P str) {
  1150. write_P(str);
  1151. println();
  1152. }