You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2025 lines
55KB

  1. /* Arduino SdFat Library
  2. * Copyright (C) 2012 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. //------------------------------------------------------------------------------
  22. // pointer to cwd directory
  23. SdBaseFile* SdBaseFile::m_cwd = 0;
  24. // callback function for date/time
  25. void (*SdBaseFile::m_dateTime)(uint16_t* date, uint16_t* time) = 0;
  26. //------------------------------------------------------------------------------
  27. // add a cluster to a file
  28. bool SdBaseFile::addCluster() {
  29. if (!m_vol->allocContiguous(1, &m_curCluster)) {
  30. DBG_FAIL_MACRO;
  31. goto fail;
  32. }
  33. // if first cluster of file link to directory entry
  34. if (m_firstCluster == 0) {
  35. m_firstCluster = m_curCluster;
  36. m_flags |= F_FILE_DIR_DIRTY;
  37. }
  38. return true;
  39. fail:
  40. return false;
  41. }
  42. //------------------------------------------------------------------------------
  43. // Add a cluster to a directory file and zero the cluster.
  44. // return with first block of cluster in the cache
  45. cache_t* SdBaseFile::addDirCluster() {
  46. uint32_t block;
  47. cache_t* pc;
  48. // max folder size
  49. if (m_fileSize/sizeof(dir_t) >= 0XFFFF) {
  50. DBG_FAIL_MACRO;
  51. goto fail;
  52. }
  53. if (!addCluster()) {
  54. DBG_FAIL_MACRO;
  55. goto fail;
  56. }
  57. block = m_vol->clusterStartBlock(m_curCluster);
  58. pc = m_vol->cacheFetch(block, SdVolume::CACHE_RESERVE_FOR_WRITE);
  59. if (!pc) {
  60. DBG_FAIL_MACRO;
  61. goto fail;
  62. }
  63. memset(pc, 0, 512);
  64. // zero rest of clusters
  65. for (uint8_t i = 1; i < m_vol->blocksPerCluster(); i++) {
  66. if (!m_vol->writeBlock(block + i, pc->data)) {
  67. DBG_FAIL_MACRO;
  68. goto fail;
  69. }
  70. }
  71. // Increase directory file size by cluster size
  72. m_fileSize += 512UL*m_vol->blocksPerCluster();
  73. return pc;
  74. fail:
  75. return 0;
  76. }
  77. //------------------------------------------------------------------------------
  78. // cache a file's directory entry
  79. // return pointer to cached entry or null for failure
  80. dir_t* SdBaseFile::cacheDirEntry(uint8_t action) {
  81. cache_t* pc;
  82. pc = m_vol->cacheFetch(m_dirBlock, action);
  83. if (!pc) {
  84. DBG_FAIL_MACRO;
  85. goto fail;
  86. }
  87. return pc->dir + m_dirIndex;
  88. fail:
  89. return 0;
  90. }
  91. //------------------------------------------------------------------------------
  92. /** Close a file and force cached data and directory information
  93. * to be written to the storage device.
  94. *
  95. * \return The value one, true, is returned for success and
  96. * the value zero, false, is returned for failure.
  97. * Reasons for failure include no file is open or an I/O error.
  98. */
  99. bool SdBaseFile::close() {
  100. bool rtn = sync();
  101. m_type = FAT_FILE_TYPE_CLOSED;
  102. return rtn;
  103. }
  104. //------------------------------------------------------------------------------
  105. /** Check for contiguous file and return its raw block range.
  106. *
  107. * \param[out] bgnBlock the first block address for the file.
  108. * \param[out] endBlock the last block address for the file.
  109. *
  110. * \return The value one, true, is returned for success and
  111. * the value zero, false, is returned for failure.
  112. * Reasons for failure include file is not contiguous, file has zero length
  113. * or an I/O error occurred.
  114. */
  115. bool SdBaseFile::contiguousRange(uint32_t* bgnBlock, uint32_t* endBlock) {
  116. // error if no blocks
  117. if (m_firstCluster == 0) {
  118. DBG_FAIL_MACRO;
  119. goto fail;
  120. }
  121. for (uint32_t c = m_firstCluster; ; c++) {
  122. uint32_t next;
  123. if (!m_vol->fatGet(c, &next)) {
  124. DBG_FAIL_MACRO;
  125. goto fail;
  126. }
  127. // check for contiguous
  128. if (next != (c + 1)) {
  129. // error if not end of chain
  130. if (!m_vol->isEOC(next)) {
  131. DBG_FAIL_MACRO;
  132. goto fail;
  133. }
  134. *bgnBlock = m_vol->clusterStartBlock(m_firstCluster);
  135. *endBlock = m_vol->clusterStartBlock(c)
  136. + m_vol->blocksPerCluster() - 1;
  137. return true;
  138. }
  139. }
  140. fail:
  141. return false;
  142. }
  143. //------------------------------------------------------------------------------
  144. /** Create and open a new contiguous file of a specified size.
  145. *
  146. * \note This function only supports short DOS 8.3 names.
  147. * See open() for more information.
  148. *
  149. * \param[in] dirFile The directory where the file will be created.
  150. * \param[in] path A path with a valid DOS 8.3 file name.
  151. * \param[in] size The desired file size.
  152. *
  153. * \return The value one, true, is returned for success and
  154. * the value zero, false, is returned for failure.
  155. * Reasons for failure include \a path contains
  156. * an invalid DOS 8.3 file name, the FAT volume has not been initialized,
  157. * a file is already open, the file already exists, the root
  158. * directory is full or an I/O error.
  159. *
  160. */
  161. bool SdBaseFile::createContiguous(SdBaseFile* dirFile,
  162. const char* path, uint32_t size) {
  163. uint32_t count;
  164. // don't allow zero length file
  165. if (size == 0) {
  166. DBG_FAIL_MACRO;
  167. goto fail;
  168. }
  169. if (!open(dirFile, path, O_CREAT | O_EXCL | O_RDWR)) {
  170. DBG_FAIL_MACRO;
  171. goto fail;
  172. }
  173. // calculate number of clusters needed
  174. count = ((size - 1) >> (m_vol->clusterSizeShift() + 9)) + 1;
  175. // allocate clusters
  176. if (!m_vol->allocContiguous(count, &m_firstCluster)) {
  177. remove();
  178. DBG_FAIL_MACRO;
  179. goto fail;
  180. }
  181. m_fileSize = size;
  182. // insure sync() will update dir entry
  183. m_flags |= F_FILE_DIR_DIRTY;
  184. return sync();
  185. fail:
  186. return false;
  187. }
  188. //------------------------------------------------------------------------------
  189. /** Return a file's directory entry.
  190. *
  191. * \param[out] dir Location for return of the file's directory entry.
  192. *
  193. * \return The value one, true, is returned for success and
  194. * the value zero, false, is returned for failure.
  195. */
  196. bool SdBaseFile::dirEntry(dir_t* dir) {
  197. dir_t* p;
  198. // make sure fields on SD are correct
  199. if (!sync()) {
  200. DBG_FAIL_MACRO;
  201. goto fail;
  202. }
  203. // read entry
  204. p = cacheDirEntry(SdVolume::CACHE_FOR_READ);
  205. if (!p) {
  206. DBG_FAIL_MACRO;
  207. goto fail;
  208. }
  209. // copy to caller's struct
  210. memcpy(dir, p, sizeof(dir_t));
  211. return true;
  212. fail:
  213. return false;
  214. }
  215. //------------------------------------------------------------------------------
  216. /** Format the name field of \a dir into the 13 byte array
  217. * \a name in standard 8.3 short name format.
  218. *
  219. * \param[in] dir The directory structure containing the name.
  220. * \param[out] name A 13 byte char array for the formatted name.
  221. */
  222. void SdBaseFile::dirName(const dir_t& dir, char* name) {
  223. uint8_t j = 0;
  224. for (uint8_t i = 0; i < 11; i++) {
  225. if (dir.name[i] == ' ')continue;
  226. if (i == 8) name[j++] = '.';
  227. name[j++] = dir.name[i];
  228. }
  229. name[j] = 0;
  230. }
  231. //------------------------------------------------------------------------------
  232. /** Test for the existence of a file in a directory
  233. *
  234. * \param[in] name Name of the file to be tested for.
  235. *
  236. * The calling instance must be an open directory file.
  237. *
  238. * dirFile.exists("TOFIND.TXT") searches for "TOFIND.TXT" in the directory
  239. * dirFile.
  240. *
  241. * \return true if the file exists else false.
  242. */
  243. bool SdBaseFile::exists(const char* name) {
  244. SdBaseFile file;
  245. return file.open(this, name, O_READ);
  246. }
  247. //------------------------------------------------------------------------------
  248. /**
  249. * Get a string from a file.
  250. *
  251. * fgets() reads bytes from a file into the array pointed to by \a str, until
  252. * \a num - 1 bytes are read, or a delimiter is read and transferred to \a str,
  253. * or end-of-file is encountered. The string is then terminated
  254. * with a null byte.
  255. *
  256. * fgets() deletes CR, '\\r', from the string. This insures only a '\\n'
  257. * terminates the string for Windows text files which use CRLF for newline.
  258. *
  259. * \param[out] str Pointer to the array where the string is stored.
  260. * \param[in] num Maximum number of characters to be read
  261. * (including the final null byte). Usually the length
  262. * of the array \a str is used.
  263. * \param[in] delim Optional set of delimiters. The default is "\n".
  264. *
  265. * \return For success fgets() returns the length of the string in \a str.
  266. * If no data is read, fgets() returns zero for EOF or -1 if an error occurred.
  267. **/
  268. int16_t SdBaseFile::fgets(char* str, int16_t num, char* delim) {
  269. char ch;
  270. int16_t n = 0;
  271. int16_t r = -1;
  272. while ((n + 1) < num && (r = read(&ch, 1)) == 1) {
  273. // delete CR
  274. if (ch == '\r') continue;
  275. str[n++] = ch;
  276. if (!delim) {
  277. if (ch == '\n') break;
  278. } else {
  279. if (strchr(delim, ch)) break;
  280. }
  281. }
  282. if (r < 0) {
  283. // read error
  284. return -1;
  285. }
  286. str[n] = '\0';
  287. return n;
  288. }
  289. //------------------------------------------------------------------------------
  290. /** Get a file's name
  291. *
  292. * \param[out] name An array of 13 characters for the file's name.
  293. *
  294. * \return The value one, true, is returned for success and
  295. * the value zero, false, is returned for failure.
  296. */
  297. bool SdBaseFile::getFilename(char* name) {
  298. dir_t* p;
  299. if (!isOpen()) {
  300. DBG_FAIL_MACRO;
  301. goto fail;
  302. }
  303. if (isRoot()) {
  304. name[0] = '/';
  305. name[1] = '\0';
  306. return true;
  307. }
  308. // cache entry
  309. p = cacheDirEntry(SdVolume::CACHE_FOR_READ);
  310. if (!p) {
  311. DBG_FAIL_MACRO;
  312. goto fail;
  313. }
  314. // format name
  315. dirName(*p, name);
  316. return true;
  317. fail:
  318. return false;
  319. }
  320. //------------------------------------------------------------------------------
  321. void SdBaseFile::getpos(FatPos_t* pos) {
  322. pos->position = m_curPosition;
  323. pos->cluster = m_curCluster;
  324. }
  325. //------------------------------------------------------------------------------
  326. // format directory name field from a 8.3 name string
  327. bool SdBaseFile::make83Name(const char* str, uint8_t* name, const char** ptr) {
  328. uint8_t c;
  329. uint8_t n = 7; // max index for part before dot
  330. uint8_t i = 0;
  331. // blank fill name and extension
  332. while (i < 11) name[i++] = ' ';
  333. i = 0;
  334. while (*str != '\0' && *str != '/') {
  335. c = *str++;
  336. if (c == '.') {
  337. if (n == 10) {
  338. // only one dot allowed
  339. DBG_FAIL_MACRO;
  340. goto fail;
  341. }
  342. n = 10; // max index for full 8.3 name
  343. i = 8; // place for extension
  344. } else {
  345. // illegal FAT characters
  346. #ifdef __AVR__
  347. // store chars in flash
  348. PGM_P p = PSTR("|<>^+=?/[];,*\"\\");
  349. uint8_t b;
  350. while ((b = pgm_read_byte(p++))) if (b == c) {
  351. DBG_FAIL_MACRO;
  352. goto fail;
  353. }
  354. #else // __AVR__
  355. // store chars in RAM
  356. if (strchr("|<>^+=?/[];,*\"\\", c)) {
  357. DBG_FAIL_MACRO;
  358. goto fail;
  359. }
  360. #endif // __AVR__
  361. // check size and only allow ASCII printable characters
  362. if (i > n || c < 0X21 || c > 0X7E) {
  363. DBG_FAIL_MACRO;
  364. goto fail;
  365. }
  366. // only upper case allowed in 8.3 names - convert lower to upper
  367. name[i++] = c < 'a' || c > 'z' ? c : c + ('A' - 'a');
  368. }
  369. }
  370. *ptr = str;
  371. // must have a file name, extension is optional
  372. return name[0] != ' ';
  373. fail:
  374. return false;
  375. }
  376. //------------------------------------------------------------------------------
  377. /** Make a new directory.
  378. *
  379. * \param[in] parent An open SdFat instance for the directory that will contain
  380. * the new directory.
  381. *
  382. * \param[in] path A path with a valid 8.3 DOS name for the new directory.
  383. *
  384. * \param[in] pFlag Create missing parent directories if true.
  385. *
  386. * \return The value one, true, is returned for success and
  387. * the value zero, false, is returned for failure.
  388. * Reasons for failure include this file is already open, \a parent is not a
  389. * directory, \a path is invalid or already exists in \a parent.
  390. */
  391. bool SdBaseFile::mkdir(SdBaseFile* parent, const char* path, bool pFlag) {
  392. uint8_t dname[11];
  393. SdBaseFile dir1, dir2;
  394. SdBaseFile* sub = &dir1;
  395. SdBaseFile* start = parent;
  396. if (!parent || isOpen()) {
  397. DBG_FAIL_MACRO;
  398. goto fail;
  399. }
  400. if (*path == '/') {
  401. while (*path == '/') path++;
  402. if (!parent->isRoot()) {
  403. if (!dir2.openRoot(parent->m_vol)) {
  404. DBG_FAIL_MACRO;
  405. goto fail;
  406. }
  407. parent = &dir2;
  408. }
  409. }
  410. while (1) {
  411. if (!make83Name(path, dname, &path)) {
  412. DBG_FAIL_MACRO;
  413. goto fail;
  414. }
  415. while (*path == '/') path++;
  416. if (!*path) break;
  417. if (!sub->open(parent, dname, O_READ)) {
  418. if (!pFlag || !sub->mkdir(parent, dname)) {
  419. DBG_FAIL_MACRO;
  420. goto fail;
  421. }
  422. }
  423. if (parent != start) parent->close();
  424. parent = sub;
  425. sub = parent != &dir1 ? &dir1 : &dir2;
  426. }
  427. return mkdir(parent, dname);
  428. fail:
  429. return false;
  430. }
  431. //------------------------------------------------------------------------------
  432. bool SdBaseFile::mkdir(SdBaseFile* parent, const uint8_t dname[11]) {
  433. uint32_t block;
  434. dir_t d;
  435. dir_t* p;
  436. cache_t* pc;
  437. if (!parent->isDir()) {
  438. DBG_FAIL_MACRO;
  439. goto fail;
  440. }
  441. // create a normal file
  442. if (!open(parent, dname, O_CREAT | O_EXCL | O_RDWR)) {
  443. DBG_FAIL_MACRO;
  444. goto fail;
  445. }
  446. // convert file to directory
  447. m_flags = O_READ;
  448. m_type = FAT_FILE_TYPE_SUBDIR;
  449. // allocate and zero first cluster
  450. if (!addDirCluster()) {
  451. DBG_FAIL_MACRO;
  452. goto fail;
  453. }
  454. // force entry to SD
  455. if (!sync()) {
  456. DBG_FAIL_MACRO;
  457. goto fail;
  458. }
  459. // cache entry - should already be in cache due to sync() call
  460. p = cacheDirEntry(SdVolume::CACHE_FOR_WRITE);
  461. if (!p) {
  462. DBG_FAIL_MACRO;
  463. goto fail;
  464. }
  465. // change directory entry attribute
  466. p->attributes = DIR_ATT_DIRECTORY;
  467. // make entry for '.'
  468. memcpy(&d, p, sizeof(d));
  469. d.name[0] = '.';
  470. for (uint8_t i = 1; i < 11; i++) d.name[i] = ' ';
  471. // cache block for '.' and '..'
  472. block = m_vol->clusterStartBlock(m_firstCluster);
  473. pc = m_vol->cacheFetch(block, SdVolume::CACHE_FOR_WRITE);
  474. if (!pc) {
  475. DBG_FAIL_MACRO;
  476. goto fail;
  477. }
  478. // copy '.' to block
  479. memcpy(&pc->dir[0], &d, sizeof(d));
  480. // make entry for '..'
  481. d.name[1] = '.';
  482. if (parent->isRoot()) {
  483. d.firstClusterLow = 0;
  484. d.firstClusterHigh = 0;
  485. } else {
  486. d.firstClusterLow = parent->m_firstCluster & 0XFFFF;
  487. d.firstClusterHigh = parent->m_firstCluster >> 16;
  488. }
  489. // copy '..' to block
  490. memcpy(&pc->dir[1], &d, sizeof(d));
  491. // write first block
  492. return m_vol->cacheSync();
  493. fail:
  494. return false;
  495. }
  496. //------------------------------------------------------------------------------
  497. /** Open a file in the current working directory.
  498. *
  499. * \param[in] path A path with a valid 8.3 DOS name for a file to be opened.
  500. *
  501. * \param[in] oflag Values for \a oflag are constructed by a bitwise-inclusive
  502. * OR of open flags. see SdBaseFile::open(SdBaseFile*, const char*, uint8_t).
  503. *
  504. * \return The value one, true, is returned for success and
  505. * the value zero, false, is returned for failure.
  506. */
  507. bool SdBaseFile::open(const char* path, uint8_t oflag) {
  508. return open(m_cwd, path, oflag);
  509. }
  510. //------------------------------------------------------------------------------
  511. /** Open a file or directory by name.
  512. *
  513. * \param[in] dirFile An open SdFat instance for the directory containing the
  514. * file to be opened.
  515. *
  516. * \param[in] path A path with a valid 8.3 DOS name for a file to be opened.
  517. *
  518. * \param[in] oflag Values for \a oflag are constructed by a bitwise-inclusive
  519. * OR of flags from the following list
  520. *
  521. * O_READ - Open for reading.
  522. *
  523. * O_RDONLY - Same as O_READ.
  524. *
  525. * O_WRITE - Open for writing.
  526. *
  527. * O_WRONLY - Same as O_WRITE.
  528. *
  529. * O_RDWR - Open for reading and writing.
  530. *
  531. * O_APPEND - If set, the file offset shall be set to the end of the
  532. * file prior to each write.
  533. *
  534. * O_AT_END - Set the initial position at the end of the file.
  535. *
  536. * O_CREAT - If the file exists, this flag has no effect except as noted
  537. * under O_EXCL below. Otherwise, the file shall be created
  538. *
  539. * O_EXCL - If O_CREAT and O_EXCL are set, open() shall fail if the file exists.
  540. *
  541. * O_SYNC - Call sync() after each write. This flag should not be used with
  542. * write(uint8_t), write_P(PGM_P), writeln_P(PGM_P), or the Arduino Print class.
  543. * These functions do character at a time writes so sync() will be called
  544. * after each byte.
  545. *
  546. * O_TRUNC - If the file exists and is a regular file, and the file is
  547. * successfully opened and is not read only, its length shall be truncated to 0.
  548. *
  549. * WARNING: A given file must not be opened by more than one SdBaseFile object
  550. * or file corruption may occur.
  551. *
  552. * \note Directory files must be opened read only. Write and truncation is
  553. * not allowed for directory files.
  554. *
  555. * \return The value one, true, is returned for success and
  556. * the value zero, false, is returned for failure.
  557. * Reasons for failure include this file is already open, \a dirFile is not
  558. * a directory, \a path is invalid, the file does not exist
  559. * or can't be opened in the access mode specified by oflag.
  560. */
  561. bool SdBaseFile::open(SdBaseFile* dirFile, const char* path, uint8_t oflag) {
  562. uint8_t dname[11];
  563. SdBaseFile dir1, dir2;
  564. SdBaseFile *parent = dirFile;
  565. SdBaseFile *sub = &dir1;
  566. if (!dirFile) {
  567. DBG_FAIL_MACRO;
  568. goto fail;
  569. }
  570. // error if already open
  571. if (isOpen()) {
  572. DBG_FAIL_MACRO;
  573. goto fail;
  574. }
  575. if (*path == '/') {
  576. while (*path == '/') path++;
  577. if (*path == 0) return openRoot(dirFile->m_vol);
  578. if (!dirFile->isRoot()) {
  579. if (!dir2.openRoot(dirFile->m_vol)) {
  580. DBG_FAIL_MACRO;
  581. goto fail;
  582. }
  583. parent = &dir2;
  584. }
  585. }
  586. while (1) {
  587. if (!make83Name(path, dname, &path)) {
  588. DBG_FAIL_MACRO;
  589. goto fail;
  590. }
  591. while (*path == '/') path++;
  592. if (!*path) break;
  593. if (!sub->open(parent, dname, O_READ)) {
  594. DBG_FAIL_MACRO;
  595. goto fail;
  596. }
  597. if (parent != dirFile) parent->close();
  598. parent = sub;
  599. sub = parent != &dir1 ? &dir1 : &dir2;
  600. }
  601. return open(parent, dname, oflag);
  602. fail:
  603. return false;
  604. }
  605. //------------------------------------------------------------------------------
  606. // open with filename in dname
  607. bool SdBaseFile::open(SdBaseFile* dirFile,
  608. const uint8_t dname[11], uint8_t oflag) {
  609. cache_t* pc;
  610. bool emptyFound = false;
  611. bool fileFound = false;
  612. uint8_t index;
  613. dir_t* p;
  614. m_vol = dirFile->m_vol;
  615. dirFile->rewind();
  616. // search for file
  617. while (dirFile->m_curPosition < dirFile->m_fileSize) {
  618. // Cache directory block.
  619. if (dirFile->read() < 0) {
  620. DBG_FAIL_MACRO;
  621. goto fail;
  622. }
  623. // Position to to next block
  624. dirFile->m_curPosition += 511;
  625. for (index = 0; index < 16; index++) {
  626. p = &m_vol->cacheAddress()->dir[index];
  627. if (p->name[0] == DIR_NAME_FREE || p->name[0] == DIR_NAME_DELETED) {
  628. // remember first empty slot
  629. if (!emptyFound) {
  630. m_dirBlock = m_vol->cacheBlockNumber();
  631. m_dirIndex = index;
  632. emptyFound = true;
  633. }
  634. // done if no entries follow
  635. if (p->name[0] == DIR_NAME_FREE) {
  636. goto done;
  637. }
  638. } else if (!memcmp(dname, p->name, 11)) {
  639. fileFound = true;
  640. goto done;
  641. }
  642. }
  643. }
  644. done:
  645. if (fileFound) {
  646. // don't open existing file if O_EXCL
  647. if (oflag & O_EXCL) {
  648. DBG_FAIL_MACRO;
  649. goto fail;
  650. }
  651. } else {
  652. // don't create unless O_CREAT and O_WRITE
  653. if (!(oflag & O_CREAT) || !(oflag & O_WRITE)) {
  654. DBG_FAIL_MACRO;
  655. goto fail;
  656. }
  657. if (emptyFound) {
  658. index = m_dirIndex;
  659. p = cacheDirEntry(SdVolume::CACHE_FOR_WRITE);
  660. if (!p) {
  661. DBG_FAIL_MACRO;
  662. goto fail;
  663. }
  664. } else {
  665. if (dirFile->m_type == FAT_FILE_TYPE_ROOT_FIXED) {
  666. DBG_FAIL_MACRO;
  667. goto fail;
  668. }
  669. // add and zero cluster for dirFile - first cluster is in cache for write
  670. pc = dirFile->addDirCluster();
  671. if (!pc) {
  672. DBG_FAIL_MACRO;
  673. goto fail;
  674. }
  675. // use first entry in cluster
  676. p = pc->dir;
  677. index = 0;
  678. }
  679. // initialize as empty file
  680. memset(p, 0, sizeof(dir_t));
  681. memcpy(p->name, dname, 11);
  682. // set timestamps
  683. if (m_dateTime) {
  684. // call user date/time function
  685. m_dateTime(&p->creationDate, &p->creationTime);
  686. } else {
  687. // use default date/time
  688. p->creationDate = FAT_DEFAULT_DATE;
  689. p->creationTime = FAT_DEFAULT_TIME;
  690. }
  691. p->lastAccessDate = p->creationDate;
  692. p->lastWriteDate = p->creationDate;
  693. p->lastWriteTime = p->creationTime;
  694. // write entry to SD
  695. if (!dirFile->m_vol->cacheSync()) {
  696. DBG_FAIL_MACRO;
  697. goto fail;
  698. }
  699. }
  700. // open entry in cache
  701. return openCachedEntry(index, oflag);
  702. fail:
  703. return false;
  704. }
  705. //------------------------------------------------------------------------------
  706. /** Open a file by index.
  707. *
  708. * \param[in] dirFile An open SdFat instance for the directory.
  709. *
  710. * \param[in] index The \a index of the directory entry for the file to be
  711. * opened. The value for \a index is (directory file position)/32.
  712. *
  713. * \param[in] oflag Values for \a oflag are constructed by a bitwise-inclusive
  714. * OR of flags O_READ, O_WRITE, O_TRUNC, and O_SYNC.
  715. *
  716. * See open() by path for definition of flags.
  717. * \return true for success or false for failure.
  718. */
  719. bool SdBaseFile::open(SdBaseFile* dirFile, uint16_t index, uint8_t oflag) {
  720. dir_t* p;
  721. m_vol = dirFile->m_vol;
  722. // error if already open
  723. if (isOpen() || !dirFile) {
  724. DBG_FAIL_MACRO;
  725. goto fail;
  726. }
  727. // don't open existing file if O_EXCL - user call error
  728. if (oflag & O_EXCL) {
  729. DBG_FAIL_MACRO;
  730. goto fail;
  731. }
  732. // seek to location of entry
  733. if (!dirFile->seekSet(32 * index)) {
  734. DBG_FAIL_MACRO;
  735. goto fail;
  736. }
  737. // read entry into cache
  738. p = dirFile->readDirCache();
  739. if (!p) {
  740. DBG_FAIL_MACRO;
  741. goto fail;
  742. }
  743. // error if empty slot or '.' or '..'
  744. if (p->name[0] == DIR_NAME_FREE ||
  745. p->name[0] == DIR_NAME_DELETED || p->name[0] == '.') {
  746. DBG_FAIL_MACRO;
  747. goto fail;
  748. }
  749. // open cached entry
  750. return openCachedEntry(index & 0XF, oflag);
  751. fail:
  752. return false;
  753. }
  754. //------------------------------------------------------------------------------
  755. // open a cached directory entry. Assumes m_vol is initialized
  756. bool SdBaseFile::openCachedEntry(uint8_t dirIndex, uint8_t oflag) {
  757. // location of entry in cache
  758. dir_t* p = &m_vol->cacheAddress()->dir[dirIndex];
  759. // write or truncate is an error for a directory or read-only file
  760. if (p->attributes & (DIR_ATT_READ_ONLY | DIR_ATT_DIRECTORY)) {
  761. if (oflag & (O_WRITE | O_TRUNC)) {
  762. DBG_FAIL_MACRO;
  763. goto fail;
  764. }
  765. }
  766. // remember location of directory entry on SD
  767. m_dirBlock = m_vol->cacheBlockNumber();
  768. m_dirIndex = dirIndex;
  769. // copy first cluster number for directory fields
  770. m_firstCluster = (uint32_t)p->firstClusterHigh << 16;
  771. m_firstCluster |= p->firstClusterLow;
  772. // make sure it is a normal file or subdirectory
  773. if (DIR_IS_FILE(p)) {
  774. m_fileSize = p->fileSize;
  775. m_type = FAT_FILE_TYPE_NORMAL;
  776. } else if (DIR_IS_SUBDIR(p)) {
  777. if (!setDirSize()) {
  778. DBG_FAIL_MACRO;
  779. goto fail;
  780. }
  781. m_type = FAT_FILE_TYPE_SUBDIR;
  782. } else {
  783. DBG_FAIL_MACRO;
  784. goto fail;
  785. }
  786. // save open flags for read/write
  787. m_flags = oflag & F_OFLAG;
  788. // set to start of file
  789. m_curCluster = 0;
  790. m_curPosition = 0;
  791. if ((oflag & O_TRUNC) && !truncate(0)) {
  792. DBG_FAIL_MACRO;
  793. goto fail;
  794. }
  795. return oflag & O_AT_END ? seekEnd(0) : true;
  796. fail:
  797. m_type = FAT_FILE_TYPE_CLOSED;
  798. return false;
  799. }
  800. //------------------------------------------------------------------------------
  801. /** Open the next file or subdirectory in a directory.
  802. *
  803. * \param[in] dirFile An open SdFat instance for the directory containing the
  804. * file to be opened.
  805. *
  806. * \param[in] oflag Values for \a oflag are constructed by a bitwise-inclusive
  807. * OR of flags O_READ, O_WRITE, O_TRUNC, and O_SYNC.
  808. *
  809. * See open() by path for definition of flags.
  810. * \return true for success or false for failure.
  811. */
  812. bool SdBaseFile::openNext(SdBaseFile* dirFile, uint8_t oflag) {
  813. dir_t* p;
  814. uint8_t index;
  815. if (!dirFile) {
  816. DBG_FAIL_MACRO;
  817. goto fail;
  818. }
  819. // error if already open
  820. if (isOpen()) {
  821. DBG_FAIL_MACRO;
  822. goto fail;
  823. }
  824. m_vol = dirFile->m_vol;
  825. while (1) {
  826. index = 0XF & (dirFile->m_curPosition >> 5);
  827. // read entry into cache
  828. p = dirFile->readDirCache();
  829. if (!p) {
  830. DBG_FAIL_MACRO;
  831. goto fail;
  832. }
  833. // done if last entry
  834. if (p->name[0] == DIR_NAME_FREE) {
  835. DBG_FAIL_MACRO;
  836. goto fail;
  837. }
  838. // skip empty slot or '.' or '..'
  839. if (p->name[0] == DIR_NAME_DELETED || p->name[0] == '.') {
  840. continue;
  841. }
  842. // must be file or dir
  843. if (DIR_IS_FILE_OR_SUBDIR(p)) {
  844. return openCachedEntry(index, oflag);
  845. }
  846. }
  847. fail:
  848. return false;
  849. }
  850. //------------------------------------------------------------------------------
  851. /** Open a directory's parent directory.
  852. *
  853. * \param[in] dir Parent of this directory will be opened. Must not be root.
  854. *
  855. * \return The value one, true, is returned for success and
  856. * the value zero, false, is returned for failure.
  857. */
  858. bool SdBaseFile::openParent(SdBaseFile* dir) {
  859. dir_t entry;
  860. dir_t* p;
  861. SdBaseFile file;
  862. uint32_t c;
  863. uint32_t cluster;
  864. uint32_t lbn;
  865. cache_t* pc;
  866. // error if already open or dir is root or dir is not a directory
  867. if (isOpen() || !dir || dir->isRoot() || !dir->isDir()) {
  868. DBG_FAIL_MACRO;
  869. goto fail;
  870. }
  871. m_vol = dir->m_vol;
  872. // position to '..'
  873. if (!dir->seekSet(32)) {
  874. DBG_FAIL_MACRO;
  875. goto fail;
  876. }
  877. // read '..' entry
  878. if (dir->read(&entry, sizeof(entry)) != 32) {
  879. DBG_FAIL_MACRO;
  880. goto fail;
  881. }
  882. // verify it is '..'
  883. if (entry.name[0] != '.' || entry.name[1] != '.') {
  884. DBG_FAIL_MACRO;
  885. goto fail;
  886. }
  887. // start cluster for '..'
  888. cluster = entry.firstClusterLow;
  889. cluster |= (uint32_t)entry.firstClusterHigh << 16;
  890. if (cluster == 0) return openRoot(m_vol);
  891. // start block for '..'
  892. lbn = m_vol->clusterStartBlock(cluster);
  893. // first block of parent dir
  894. pc = m_vol->cacheFetch(lbn, SdVolume::CACHE_FOR_READ);
  895. if (!pc) {
  896. DBG_FAIL_MACRO;
  897. goto fail;
  898. }
  899. p = &pc->dir[1];
  900. // verify name for '../..'
  901. if (p->name[0] != '.' || p->name[1] != '.') {
  902. DBG_FAIL_MACRO;
  903. goto fail;
  904. }
  905. // '..' is pointer to first cluster of parent. open '../..' to find parent
  906. if (p->firstClusterHigh == 0 && p->firstClusterLow == 0) {
  907. if (!file.openRoot(dir->volume())) {
  908. DBG_FAIL_MACRO;
  909. goto fail;
  910. }
  911. } else {
  912. if (!file.openCachedEntry(1, O_READ)) {
  913. DBG_FAIL_MACRO;
  914. goto fail;
  915. }
  916. }
  917. // search for parent in '../..'
  918. do {
  919. if (file.readDir(&entry) != 32) {
  920. DBG_FAIL_MACRO;
  921. goto fail;
  922. }
  923. c = entry.firstClusterLow;
  924. c |= (uint32_t)entry.firstClusterHigh << 16;
  925. } while (c != cluster);
  926. // open parent
  927. return open(&file, file.curPosition()/32 - 1, O_READ);
  928. fail:
  929. return false;
  930. }
  931. //------------------------------------------------------------------------------
  932. /** Open a volume's root directory.
  933. *
  934. * \param[in] vol The FAT volume containing the root directory to be opened.
  935. *
  936. * \return The value one, true, is returned for success and
  937. * the value zero, false, is returned for failure.
  938. * Reasons for failure include the file is already open, the FAT volume has
  939. * not been initialized or it a FAT12 volume.
  940. */
  941. bool SdBaseFile::openRoot(SdVolume* vol) {
  942. // error if file is already open
  943. if (isOpen()) {
  944. DBG_FAIL_MACRO;
  945. goto fail;
  946. }
  947. m_vol = vol;
  948. if (vol->fatType() == 16 || (FAT12_SUPPORT && vol->fatType() == 12)) {
  949. m_type = FAT_FILE_TYPE_ROOT_FIXED;
  950. m_firstCluster = 0;
  951. m_fileSize = 32 * vol->rootDirEntryCount();
  952. } else if (vol->fatType() == 32) {
  953. m_type = FAT_FILE_TYPE_ROOT32;
  954. m_firstCluster = vol->rootDirStart();
  955. if (!setDirSize()) {
  956. DBG_FAIL_MACRO;
  957. goto fail;
  958. }
  959. } else {
  960. // volume is not initialized, invalid, or FAT12 without support
  961. DBG_FAIL_MACRO;
  962. goto fail;
  963. }
  964. // read only
  965. m_flags = O_READ;
  966. // set to start of file
  967. m_curCluster = 0;
  968. m_curPosition = 0;
  969. // root has no directory entry
  970. m_dirBlock = 0;
  971. m_dirIndex = 0;
  972. return true;
  973. fail:
  974. return false;
  975. }
  976. //------------------------------------------------------------------------------
  977. /** Return the next available byte without consuming it.
  978. *
  979. * \return The byte if no error and not at eof else -1;
  980. */
  981. int SdBaseFile::peek() {
  982. FatPos_t pos;
  983. getpos(&pos);
  984. int c = read();
  985. if (c >= 0) setpos(&pos);
  986. return c;
  987. }
  988. //------------------------------------------------------------------------------
  989. /** Read the next byte from a file.
  990. *
  991. * \return For success read returns the next byte in the file as an int.
  992. * If an error occurs or end of file is reached -1 is returned.
  993. */
  994. int16_t SdBaseFile::read() {
  995. uint8_t b;
  996. return read(&b, 1) == 1 ? b : -1;
  997. }
  998. //------------------------------------------------------------------------------
  999. /** Read data from a file starting at the current position.
  1000. *
  1001. * \param[out] buf Pointer to the location that will receive the data.
  1002. *
  1003. * \param[in] nbyte Maximum number of bytes to read.
  1004. *
  1005. * \return For success read() returns the number of bytes read.
  1006. * A value less than \a nbyte, including zero, will be returned
  1007. * if end of file is reached.
  1008. * If an error occurs, read() returns -1. Possible errors include
  1009. * read() called before a file has been opened, corrupt file system
  1010. * or an I/O error occurred.
  1011. */
  1012. int SdBaseFile::read(void* buf, size_t nbyte) {
  1013. uint8_t blockOfCluster;
  1014. uint8_t* dst = reinterpret_cast<uint8_t*>(buf);
  1015. uint16_t offset;
  1016. size_t toRead;
  1017. uint32_t block; // raw device block number
  1018. cache_t* pc;
  1019. // error if not open or write only
  1020. if (!isOpen() || !(m_flags & O_READ)) {
  1021. DBG_FAIL_MACRO;
  1022. goto fail;
  1023. }
  1024. // max bytes left in file
  1025. if (nbyte >= (m_fileSize - m_curPosition)) {
  1026. nbyte = m_fileSize - m_curPosition;
  1027. }
  1028. // amount left to read
  1029. toRead = nbyte;
  1030. while (toRead > 0) {
  1031. size_t n;
  1032. offset = m_curPosition & 0X1FF; // offset in block
  1033. blockOfCluster = m_vol->blockOfCluster(m_curPosition);
  1034. if (m_type == FAT_FILE_TYPE_ROOT_FIXED) {
  1035. block = m_vol->rootDirStart() + (m_curPosition >> 9);
  1036. } else {
  1037. if (offset == 0 && blockOfCluster == 0) {
  1038. // start of new cluster
  1039. if (m_curPosition == 0) {
  1040. // use first cluster in file
  1041. m_curCluster = m_firstCluster;
  1042. } else {
  1043. // get next cluster from FAT
  1044. if (!m_vol->fatGet(m_curCluster, &m_curCluster)) {
  1045. DBG_FAIL_MACRO;
  1046. goto fail;
  1047. }
  1048. }
  1049. }
  1050. block = m_vol->clusterStartBlock(m_curCluster) + blockOfCluster;
  1051. }
  1052. if (offset != 0 || toRead < 512 || block == m_vol->cacheBlockNumber()) {
  1053. // amount to be read from current block
  1054. n = 512 - offset;
  1055. if (n > toRead) n = toRead;
  1056. // read block to cache and copy data to caller
  1057. pc = m_vol->cacheFetch(block, SdVolume::CACHE_FOR_READ);
  1058. if (!pc) {
  1059. DBG_FAIL_MACRO;
  1060. goto fail;
  1061. }
  1062. uint8_t* src = pc->data + offset;
  1063. memcpy(dst, src, n);
  1064. } else if (!USE_MULTI_BLOCK_SD_IO || toRead < 1024) {
  1065. // read single block
  1066. n = 512;
  1067. if (!m_vol->readBlock(block, dst)) {
  1068. DBG_FAIL_MACRO;
  1069. goto fail;
  1070. }
  1071. } else {
  1072. uint8_t nb = toRead >> 9;
  1073. if (m_type != FAT_FILE_TYPE_ROOT_FIXED) {
  1074. uint8_t mb = m_vol->blocksPerCluster() - blockOfCluster;
  1075. if (mb < nb) nb = mb;
  1076. }
  1077. n = 512*nb;
  1078. if (m_vol->cacheBlockNumber() <= block
  1079. && block < (m_vol->cacheBlockNumber() + nb)) {
  1080. // flush cache if a block is in the cache
  1081. if (!m_vol->cacheSync()) {
  1082. DBG_FAIL_MACRO;
  1083. goto fail;
  1084. }
  1085. }
  1086. if (!m_vol->sdCard()->readStart(block)) {
  1087. DBG_FAIL_MACRO;
  1088. goto fail;
  1089. }
  1090. for (uint8_t b = 0; b < nb; b++) {
  1091. if (!m_vol->sdCard()->readData(dst + b*512)) {
  1092. DBG_FAIL_MACRO;
  1093. goto fail;
  1094. }
  1095. }
  1096. if (!m_vol->sdCard()->readStop()) {
  1097. DBG_FAIL_MACRO;
  1098. goto fail;
  1099. }
  1100. }
  1101. dst += n;
  1102. m_curPosition += n;
  1103. toRead -= n;
  1104. }
  1105. return nbyte;
  1106. fail:
  1107. return -1;
  1108. }
  1109. //------------------------------------------------------------------------------
  1110. /** Read the next directory entry from a directory file.
  1111. *
  1112. * \param[out] dir The dir_t struct that will receive the data.
  1113. *
  1114. * \return For success readDir() returns the number of bytes read.
  1115. * A value of zero will be returned if end of file is reached.
  1116. * If an error occurs, readDir() returns -1. Possible errors include
  1117. * readDir() called before a directory has been opened, this is not
  1118. * a directory file or an I/O error occurred.
  1119. */
  1120. int8_t SdBaseFile::readDir(dir_t* dir) {
  1121. int16_t n;
  1122. // if not a directory file or miss-positioned return an error
  1123. if (!isDir() || (0X1F & m_curPosition)) return -1;
  1124. while (1) {
  1125. n = read(dir, sizeof(dir_t));
  1126. if (n != sizeof(dir_t)) return n == 0 ? 0 : -1;
  1127. // last entry if DIR_NAME_FREE
  1128. if (dir->name[0] == DIR_NAME_FREE) return 0;
  1129. // skip empty entries and entry for . and ..
  1130. if (dir->name[0] == DIR_NAME_DELETED || dir->name[0] == '.') continue;
  1131. // return if normal file or subdirectory
  1132. if (DIR_IS_FILE_OR_SUBDIR(dir)) return n;
  1133. }
  1134. }
  1135. //------------------------------------------------------------------------------
  1136. // Read next directory entry into the cache
  1137. // Assumes file is correctly positioned
  1138. dir_t* SdBaseFile::readDirCache() {
  1139. uint8_t i;
  1140. // error if not directory
  1141. if (!isDir()) {
  1142. DBG_FAIL_MACRO;
  1143. goto fail;
  1144. }
  1145. // index of entry in cache
  1146. i = (m_curPosition >> 5) & 0XF;
  1147. // use read to locate and cache block
  1148. if (read() < 0) {
  1149. DBG_FAIL_MACRO;
  1150. goto fail;
  1151. }
  1152. // advance to next entry
  1153. m_curPosition += 31;
  1154. // return pointer to entry
  1155. return m_vol->cacheAddress()->dir + i;
  1156. fail:
  1157. return 0;
  1158. }
  1159. //------------------------------------------------------------------------------
  1160. /** Remove a file.
  1161. *
  1162. * The directory entry and all data for the file are deleted.
  1163. *
  1164. * \note This function should not be used to delete the 8.3 version of a
  1165. * file that has a long name. For example if a file has the long name
  1166. * "New Text Document.txt" you should not delete the 8.3 name "NEWTEX~1.TXT".
  1167. *
  1168. * \return The value one, true, is returned for success and
  1169. * the value zero, false, is returned for failure.
  1170. * Reasons for failure include the file read-only, is a directory,
  1171. * or an I/O error occurred.
  1172. */
  1173. bool SdBaseFile::remove() {
  1174. dir_t* d;
  1175. // free any clusters - will fail if read-only or directory
  1176. if (!truncate(0)) {
  1177. DBG_FAIL_MACRO;
  1178. goto fail;
  1179. }
  1180. // cache directory entry
  1181. d = cacheDirEntry(SdVolume::CACHE_FOR_WRITE);
  1182. if (!d) {
  1183. DBG_FAIL_MACRO;
  1184. goto fail;
  1185. }
  1186. // mark entry deleted
  1187. d->name[0] = DIR_NAME_DELETED;
  1188. // set this file closed
  1189. m_type = FAT_FILE_TYPE_CLOSED;
  1190. // write entry to SD
  1191. return m_vol->cacheSync();
  1192. return true;
  1193. fail:
  1194. return false;
  1195. }
  1196. //------------------------------------------------------------------------------
  1197. /** Remove a file.
  1198. *
  1199. * The directory entry and all data for the file are deleted.
  1200. *
  1201. * \param[in] dirFile The directory that contains the file.
  1202. * \param[in] path Path for the file to be removed.
  1203. *
  1204. * \note This function should not be used to delete the 8.3 version of a
  1205. * file that has a long name. For example if a file has the long name
  1206. * "New Text Document.txt" you should not delete the 8.3 name "NEWTEX~1.TXT".
  1207. *
  1208. * \return The value one, true, is returned for success and
  1209. * the value zero, false, is returned for failure.
  1210. * Reasons for failure include the file is a directory, is read only,
  1211. * \a dirFile is not a directory, \a path is not found
  1212. * or an I/O error occurred.
  1213. */
  1214. bool SdBaseFile::remove(SdBaseFile* dirFile, const char* path) {
  1215. SdBaseFile file;
  1216. if (!file.open(dirFile, path, O_WRITE)) {
  1217. DBG_FAIL_MACRO;
  1218. goto fail;
  1219. }
  1220. return file.remove();
  1221. fail:
  1222. return false;
  1223. }
  1224. //------------------------------------------------------------------------------
  1225. /** Rename a file or subdirectory.
  1226. *
  1227. * \param[in] dirFile Directory for the new path.
  1228. * \param[in] newPath New path name for the file/directory.
  1229. *
  1230. * \return The value one, true, is returned for success and
  1231. * the value zero, false, is returned for failure.
  1232. * Reasons for failure include \a dirFile is not open or is not a directory
  1233. * file, newPath is invalid or already exists, or an I/O error occurs.
  1234. */
  1235. bool SdBaseFile::rename(SdBaseFile* dirFile, const char* newPath) {
  1236. dir_t entry;
  1237. uint32_t dirCluster = 0;
  1238. SdBaseFile file;
  1239. cache_t* pc;
  1240. dir_t* d;
  1241. // must be an open file or subdirectory
  1242. if (!(isFile() || isSubDir())) {
  1243. DBG_FAIL_MACRO;
  1244. goto fail;
  1245. }
  1246. // can't move file
  1247. if (m_vol != dirFile->m_vol) {
  1248. DBG_FAIL_MACRO;
  1249. goto fail;
  1250. }
  1251. // sync() and cache directory entry
  1252. sync();
  1253. d = cacheDirEntry(SdVolume::CACHE_FOR_WRITE);
  1254. if (!d) {
  1255. DBG_FAIL_MACRO;
  1256. goto fail;
  1257. }
  1258. // save directory entry
  1259. memcpy(&entry, d, sizeof(entry));
  1260. // mark entry deleted
  1261. d->name[0] = DIR_NAME_DELETED;
  1262. // make directory entry for new path
  1263. if (isFile()) {
  1264. if (!file.open(dirFile, newPath, O_CREAT | O_EXCL | O_WRITE)) {
  1265. goto restore;
  1266. }
  1267. } else {
  1268. // don't create missing path prefix components
  1269. if (!file.mkdir(dirFile, newPath, false)) {
  1270. goto restore;
  1271. }
  1272. // save cluster containing new dot dot
  1273. dirCluster = file.m_firstCluster;
  1274. }
  1275. // change to new directory entry
  1276. m_dirBlock = file.m_dirBlock;
  1277. m_dirIndex = file.m_dirIndex;
  1278. // mark closed to avoid possible destructor close call
  1279. file.m_type = FAT_FILE_TYPE_CLOSED;
  1280. // cache new directory entry
  1281. d = cacheDirEntry(SdVolume::CACHE_FOR_WRITE);
  1282. if (!d) {
  1283. DBG_FAIL_MACRO;
  1284. goto fail;
  1285. }
  1286. // copy all but name field to new directory entry
  1287. memcpy(&d->attributes, &entry.attributes, sizeof(entry) - sizeof(d->name));
  1288. // update dot dot if directory
  1289. if (dirCluster) {
  1290. // get new dot dot
  1291. uint32_t block = m_vol->clusterStartBlock(dirCluster);
  1292. pc = m_vol->cacheFetch(block, SdVolume::CACHE_FOR_READ);
  1293. if (!pc) {
  1294. DBG_FAIL_MACRO;
  1295. goto fail;
  1296. }
  1297. memcpy(&entry, &pc->dir[1], sizeof(entry));
  1298. // free unused cluster
  1299. if (!m_vol->freeChain(dirCluster)) {
  1300. DBG_FAIL_MACRO;
  1301. goto fail;
  1302. }
  1303. // store new dot dot
  1304. block = m_vol->clusterStartBlock(m_firstCluster);
  1305. pc = m_vol->cacheFetch(block, SdVolume::CACHE_FOR_WRITE);
  1306. if (!pc) {
  1307. DBG_FAIL_MACRO;
  1308. goto fail;
  1309. }
  1310. memcpy(&pc->dir[1], &entry, sizeof(entry));
  1311. }
  1312. return m_vol->cacheSync();
  1313. restore:
  1314. d = cacheDirEntry(SdVolume::CACHE_FOR_WRITE);
  1315. if (!d) {
  1316. DBG_FAIL_MACRO;
  1317. goto fail;
  1318. }
  1319. // restore entry
  1320. d->name[0] = entry.name[0];
  1321. m_vol->cacheSync();
  1322. fail:
  1323. return false;
  1324. }
  1325. //------------------------------------------------------------------------------
  1326. /** Remove a directory file.
  1327. *
  1328. * The directory file will be removed only if it is empty and is not the
  1329. * root directory. rmdir() follows DOS and Windows and ignores the
  1330. * read-only attribute for the directory.
  1331. *
  1332. * \note This function should not be used to delete the 8.3 version of a
  1333. * directory that has a long name. For example if a directory has the
  1334. * long name "New folder" you should not delete the 8.3 name "NEWFOL~1".
  1335. *
  1336. * \return The value one, true, is returned for success and
  1337. * the value zero, false, is returned for failure.
  1338. * Reasons for failure include the file is not a directory, is the root
  1339. * directory, is not empty, or an I/O error occurred.
  1340. */
  1341. bool SdBaseFile::rmdir() {
  1342. // must be open subdirectory
  1343. if (!isSubDir()) {
  1344. DBG_FAIL_MACRO;
  1345. goto fail;
  1346. }
  1347. rewind();
  1348. // make sure directory is empty
  1349. while (m_curPosition < m_fileSize) {
  1350. dir_t* p = readDirCache();
  1351. if (!p) {
  1352. DBG_FAIL_MACRO;
  1353. goto fail;
  1354. }
  1355. // done if past last used entry
  1356. if (p->name[0] == DIR_NAME_FREE) break;
  1357. // skip empty slot, '.' or '..'
  1358. if (p->name[0] == DIR_NAME_DELETED || p->name[0] == '.') continue;
  1359. // error not empty
  1360. if (DIR_IS_FILE_OR_SUBDIR(p)) {
  1361. DBG_FAIL_MACRO;
  1362. goto fail;
  1363. }
  1364. }
  1365. // convert empty directory to normal file for remove
  1366. m_type = FAT_FILE_TYPE_NORMAL;
  1367. m_flags |= O_WRITE;
  1368. return remove();
  1369. fail:
  1370. return false;
  1371. }
  1372. //------------------------------------------------------------------------------
  1373. /** Recursively delete a directory and all contained files.
  1374. *
  1375. * This is like the Unix/Linux 'rm -rf *' if called with the root directory
  1376. * hence the name.
  1377. *
  1378. * Warning - This will remove all contents of the directory including
  1379. * subdirectories. The directory will then be removed if it is not root.
  1380. * The read-only attribute for files will be ignored.
  1381. *
  1382. * \note This function should not be used to delete the 8.3 version of
  1383. * a directory that has a long name. See remove() and rmdir().
  1384. *
  1385. * \return The value one, true, is returned for success and
  1386. * the value zero, false, is returned for failure.
  1387. */
  1388. bool SdBaseFile::rmRfStar() {
  1389. uint16_t index;
  1390. SdBaseFile f;
  1391. rewind();
  1392. while (m_curPosition < m_fileSize) {
  1393. // remember position
  1394. index = m_curPosition/32;
  1395. dir_t* p = readDirCache();
  1396. if (!p) {
  1397. DBG_FAIL_MACRO;
  1398. goto fail;
  1399. }
  1400. // done if past last entry
  1401. if (p->name[0] == DIR_NAME_FREE) break;
  1402. // skip empty slot or '.' or '..'
  1403. if (p->name[0] == DIR_NAME_DELETED || p->name[0] == '.') continue;
  1404. // skip if part of long file name or volume label in root
  1405. if (!DIR_IS_FILE_OR_SUBDIR(p)) continue;
  1406. if (!f.open(this, index, O_READ)) {
  1407. DBG_FAIL_MACRO;
  1408. goto fail;
  1409. }
  1410. if (f.isSubDir()) {
  1411. // recursively delete
  1412. if (!f.rmRfStar()) {
  1413. DBG_FAIL_MACRO;
  1414. goto fail;
  1415. }
  1416. } else {
  1417. // ignore read-only
  1418. f.m_flags |= O_WRITE;
  1419. if (!f.remove()) {
  1420. DBG_FAIL_MACRO;
  1421. goto fail;
  1422. }
  1423. }
  1424. // position to next entry if required
  1425. if (m_curPosition != (32UL*(index + 1))) {
  1426. if (!seekSet(32UL*(index + 1))) {
  1427. DBG_FAIL_MACRO;
  1428. goto fail;
  1429. }
  1430. }
  1431. }
  1432. // don't try to delete root
  1433. if (!isRoot()) {
  1434. if (!rmdir()) {
  1435. DBG_FAIL_MACRO;
  1436. goto fail;
  1437. }
  1438. }
  1439. return true;
  1440. fail:
  1441. return false;
  1442. }
  1443. //------------------------------------------------------------------------------
  1444. /** Create a file object and open it in the current working directory.
  1445. *
  1446. * \param[in] path A path with a valid 8.3 DOS name for a file to be opened.
  1447. *
  1448. * \param[in] oflag Values for \a oflag are constructed by a bitwise-inclusive
  1449. * OR of open flags. see SdBaseFile::open(SdBaseFile*, const char*, uint8_t).
  1450. */
  1451. SdBaseFile::SdBaseFile(const char* path, uint8_t oflag) {
  1452. m_type = FAT_FILE_TYPE_CLOSED;
  1453. writeError = false;
  1454. open(path, oflag);
  1455. }
  1456. //------------------------------------------------------------------------------
  1457. /** Sets a file's position.
  1458. *
  1459. * \param[in] pos The new position in bytes from the beginning of the file.
  1460. *
  1461. * \return The value one, true, is returned for success and
  1462. * the value zero, false, is returned for failure.
  1463. */
  1464. bool SdBaseFile::seekSet(uint32_t pos) {
  1465. uint32_t nCur;
  1466. uint32_t nNew;
  1467. // error if file not open or seek past end of file
  1468. if (!isOpen() || pos > m_fileSize) {
  1469. DBG_FAIL_MACRO;
  1470. goto fail;
  1471. }
  1472. if (m_type == FAT_FILE_TYPE_ROOT_FIXED) {
  1473. m_curPosition = pos;
  1474. goto done;
  1475. }
  1476. if (pos == 0) {
  1477. // set position to start of file
  1478. m_curCluster = 0;
  1479. m_curPosition = 0;
  1480. goto done;
  1481. }
  1482. // calculate cluster index for cur and new position
  1483. nCur = (m_curPosition - 1) >> (m_vol->clusterSizeShift() + 9);
  1484. nNew = (pos - 1) >> (m_vol->clusterSizeShift() + 9);
  1485. if (nNew < nCur || m_curPosition == 0) {
  1486. // must follow chain from first cluster
  1487. m_curCluster = m_firstCluster;
  1488. } else {
  1489. // advance from curPosition
  1490. nNew -= nCur;
  1491. }
  1492. while (nNew--) {
  1493. if (!m_vol->fatGet(m_curCluster, &m_curCluster)) {
  1494. DBG_FAIL_MACRO;
  1495. goto fail;
  1496. }
  1497. }
  1498. m_curPosition = pos;
  1499. done:
  1500. return true;
  1501. fail:
  1502. return false;
  1503. }
  1504. //------------------------------------------------------------------------------
  1505. // set m_fileSize for a directory
  1506. bool SdBaseFile::setDirSize() {
  1507. uint16_t s = 0;
  1508. uint32_t cluster = m_firstCluster;
  1509. do {
  1510. if (!m_vol->fatGet(cluster, &cluster)) {
  1511. DBG_FAIL_MACRO;
  1512. goto fail;
  1513. }
  1514. s += m_vol->blocksPerCluster();
  1515. // max size if a directory file is 4096 blocks
  1516. if (s >= 4096) {
  1517. DBG_FAIL_MACRO;
  1518. goto fail;
  1519. }
  1520. } while (!m_vol->isEOC(cluster));
  1521. m_fileSize = 512L*s;
  1522. return true;
  1523. fail:
  1524. return false;
  1525. }
  1526. //------------------------------------------------------------------------------
  1527. void SdBaseFile::setpos(FatPos_t* pos) {
  1528. m_curPosition = pos->position;
  1529. m_curCluster = pos->cluster;
  1530. }
  1531. //------------------------------------------------------------------------------
  1532. /** The sync() call causes all modified data and directory fields
  1533. * to be written to the storage device.
  1534. *
  1535. * \return The value one, true, is returned for success and
  1536. * the value zero, false, is returned for failure.
  1537. * Reasons for failure include a call to sync() before a file has been
  1538. * opened or an I/O error.
  1539. */
  1540. bool SdBaseFile::sync() {
  1541. // only allow open files and directories
  1542. if (!isOpen()) {
  1543. DBG_FAIL_MACRO;
  1544. goto fail;
  1545. }
  1546. if (m_flags & F_FILE_DIR_DIRTY) {
  1547. dir_t* d = cacheDirEntry(SdVolume::CACHE_FOR_WRITE);
  1548. // check for deleted by another open file object
  1549. if (!d || d->name[0] == DIR_NAME_DELETED) {
  1550. DBG_FAIL_MACRO;
  1551. goto fail;
  1552. }
  1553. // do not set filesize for dir files
  1554. if (!isDir()) d->fileSize = m_fileSize;
  1555. // update first cluster fields
  1556. d->firstClusterLow = m_firstCluster & 0XFFFF;
  1557. d->firstClusterHigh = m_firstCluster >> 16;
  1558. // set modify time if user supplied a callback date/time function
  1559. if (m_dateTime) {
  1560. m_dateTime(&d->lastWriteDate, &d->lastWriteTime);
  1561. d->lastAccessDate = d->lastWriteDate;
  1562. }
  1563. // clear directory dirty
  1564. m_flags &= ~F_FILE_DIR_DIRTY;
  1565. }
  1566. return m_vol->cacheSync();
  1567. fail:
  1568. writeError = true;
  1569. return false;
  1570. }
  1571. //------------------------------------------------------------------------------
  1572. /** Copy a file's timestamps
  1573. *
  1574. * \param[in] file File to copy timestamps from.
  1575. *
  1576. * \note
  1577. * Modify and access timestamps may be overwritten if a date time callback
  1578. * function has been set by dateTimeCallback().
  1579. *
  1580. * \return The value one, true, is returned for success and
  1581. * the value zero, false, is returned for failure.
  1582. */
  1583. bool SdBaseFile::timestamp(SdBaseFile* file) {
  1584. dir_t* d;
  1585. dir_t dir;
  1586. // get timestamps
  1587. if (!file->dirEntry(&dir)) {
  1588. DBG_FAIL_MACRO;
  1589. goto fail;
  1590. }
  1591. // update directory fields
  1592. if (!sync()) {
  1593. DBG_FAIL_MACRO;
  1594. goto fail;
  1595. }
  1596. d = cacheDirEntry(SdVolume::CACHE_FOR_WRITE);
  1597. if (!d) {
  1598. DBG_FAIL_MACRO;
  1599. goto fail;
  1600. }
  1601. // copy timestamps
  1602. d->lastAccessDate = dir.lastAccessDate;
  1603. d->creationDate = dir.creationDate;
  1604. d->creationTime = dir.creationTime;
  1605. d->creationTimeTenths = dir.creationTimeTenths;
  1606. d->lastWriteDate = dir.lastWriteDate;
  1607. d->lastWriteTime = dir.lastWriteTime;
  1608. // write back entry
  1609. return m_vol->cacheSync();
  1610. fail:
  1611. return false;
  1612. }
  1613. //------------------------------------------------------------------------------
  1614. /** Set a file's timestamps in its directory entry.
  1615. *
  1616. * \param[in] flags Values for \a flags are constructed by a bitwise-inclusive
  1617. * OR of flags from the following list
  1618. *
  1619. * T_ACCESS - Set the file's last access date.
  1620. *
  1621. * T_CREATE - Set the file's creation date and time.
  1622. *
  1623. * T_WRITE - Set the file's last write/modification date and time.
  1624. *
  1625. * \param[in] year Valid range 1980 - 2107 inclusive.
  1626. *
  1627. * \param[in] month Valid range 1 - 12 inclusive.
  1628. *
  1629. * \param[in] day Valid range 1 - 31 inclusive.
  1630. *
  1631. * \param[in] hour Valid range 0 - 23 inclusive.
  1632. *
  1633. * \param[in] minute Valid range 0 - 59 inclusive.
  1634. *
  1635. * \param[in] second Valid range 0 - 59 inclusive
  1636. *
  1637. * \note It is possible to set an invalid date since there is no check for
  1638. * the number of days in a month.
  1639. *
  1640. * \note
  1641. * Modify and access timestamps may be overwritten if a date time callback
  1642. * function has been set by dateTimeCallback().
  1643. *
  1644. * \return The value one, true, is returned for success and
  1645. * the value zero, false, is returned for failure.
  1646. */
  1647. bool SdBaseFile::timestamp(uint8_t flags, uint16_t year, uint8_t month,
  1648. uint8_t day, uint8_t hour, uint8_t minute, uint8_t second) {
  1649. uint16_t dirDate;
  1650. uint16_t dirTime;
  1651. dir_t* d;
  1652. if (!isOpen()
  1653. || year < 1980
  1654. || year > 2107
  1655. || month < 1
  1656. || month > 12
  1657. || day < 1
  1658. || day > 31
  1659. || hour > 23
  1660. || minute > 59
  1661. || second > 59) {
  1662. DBG_FAIL_MACRO;
  1663. goto fail;
  1664. }
  1665. // update directory entry
  1666. if (!sync()) {
  1667. DBG_FAIL_MACRO;
  1668. goto fail;
  1669. }
  1670. d = cacheDirEntry(SdVolume::CACHE_FOR_WRITE);
  1671. if (!d) {
  1672. DBG_FAIL_MACRO;
  1673. goto fail;
  1674. }
  1675. dirDate = FAT_DATE(year, month, day);
  1676. dirTime = FAT_TIME(hour, minute, second);
  1677. if (flags & T_ACCESS) {
  1678. d->lastAccessDate = dirDate;
  1679. }
  1680. if (flags & T_CREATE) {
  1681. d->creationDate = dirDate;
  1682. d->creationTime = dirTime;
  1683. // seems to be units of 1/100 second not 1/10 as Microsoft states
  1684. d->creationTimeTenths = second & 1 ? 100 : 0;
  1685. }
  1686. if (flags & T_WRITE) {
  1687. d->lastWriteDate = dirDate;
  1688. d->lastWriteTime = dirTime;
  1689. }
  1690. return m_vol->cacheSync();
  1691. fail:
  1692. return false;
  1693. }
  1694. //------------------------------------------------------------------------------
  1695. /** Truncate a file to a specified length. The current file position
  1696. * will be maintained if it is less than or equal to \a length otherwise
  1697. * it will be set to end of file.
  1698. *
  1699. * \param[in] length The desired length for the file.
  1700. *
  1701. * \return The value one, true, is returned for success and
  1702. * the value zero, false, is returned for failure.
  1703. * Reasons for failure include file is read only, file is a directory,
  1704. * \a length is greater than the current file size or an I/O error occurs.
  1705. */
  1706. bool SdBaseFile::truncate(uint32_t length) {
  1707. uint32_t newPos;
  1708. // error if not a normal file or read-only
  1709. if (!isFile() || !(m_flags & O_WRITE)) {
  1710. DBG_FAIL_MACRO;
  1711. goto fail;
  1712. }
  1713. // error if length is greater than current size
  1714. if (length > m_fileSize) {
  1715. DBG_FAIL_MACRO;
  1716. goto fail;
  1717. }
  1718. // fileSize and length are zero - nothing to do
  1719. if (m_fileSize == 0) return true;
  1720. // remember position for seek after truncation
  1721. newPos = m_curPosition > length ? length : m_curPosition;
  1722. // position to last cluster in truncated file
  1723. if (!seekSet(length)) {
  1724. DBG_FAIL_MACRO;
  1725. goto fail;
  1726. }
  1727. if (length == 0) {
  1728. // free all clusters
  1729. if (!m_vol->freeChain(m_firstCluster)) {
  1730. DBG_FAIL_MACRO;
  1731. goto fail;
  1732. }
  1733. m_firstCluster = 0;
  1734. } else {
  1735. uint32_t toFree;
  1736. if (!m_vol->fatGet(m_curCluster, &toFree)) {
  1737. DBG_FAIL_MACRO;
  1738. goto fail;
  1739. }
  1740. if (!m_vol->isEOC(toFree)) {
  1741. // free extra clusters
  1742. if (!m_vol->freeChain(toFree)) {
  1743. DBG_FAIL_MACRO;
  1744. goto fail;
  1745. }
  1746. // current cluster is end of chain
  1747. if (!m_vol->fatPutEOC(m_curCluster)) {
  1748. DBG_FAIL_MACRO;
  1749. goto fail;
  1750. }
  1751. }
  1752. }
  1753. m_fileSize = length;
  1754. // need to update directory entry
  1755. m_flags |= F_FILE_DIR_DIRTY;
  1756. if (!sync()) {
  1757. DBG_FAIL_MACRO;
  1758. goto fail;
  1759. }
  1760. // set file to correct position
  1761. return seekSet(newPos);
  1762. fail:
  1763. return false;
  1764. }
  1765. //------------------------------------------------------------------------------
  1766. /** Write data to an open file.
  1767. *
  1768. * \note Data is moved to the cache but may not be written to the
  1769. * storage device until sync() is called.
  1770. *
  1771. * \param[in] buf Pointer to the location of the data to be written.
  1772. *
  1773. * \param[in] nbyte Number of bytes to write.
  1774. *
  1775. * \return For success write() returns the number of bytes written, always
  1776. * \a nbyte. If an error occurs, write() returns -1. Possible errors
  1777. * include write() is called before a file has been opened, write is called
  1778. * for a read-only file, device is full, a corrupt file system or an I/O error.
  1779. *
  1780. */
  1781. int SdBaseFile::write(const void* buf, size_t nbyte) {
  1782. // convert void* to uint8_t* - must be before goto statements
  1783. const uint8_t* src = reinterpret_cast<const uint8_t*>(buf);
  1784. cache_t* pc;
  1785. uint8_t cacheOption;
  1786. // number of bytes left to write - must be before goto statements
  1787. size_t nToWrite = nbyte;
  1788. size_t n;
  1789. // error if not a normal file or is read-only
  1790. if (!isFile() || !(m_flags & O_WRITE)) {
  1791. DBG_FAIL_MACRO;
  1792. goto fail;
  1793. }
  1794. // seek to end of file if append flag
  1795. if ((m_flags & O_APPEND) && m_curPosition != m_fileSize) {
  1796. if (!seekEnd()) {
  1797. DBG_FAIL_MACRO;
  1798. goto fail;
  1799. }
  1800. }
  1801. // Don't exceed max fileSize.
  1802. if (nbyte > (0XFFFFFFFF - m_curPosition)) {
  1803. DBG_FAIL_MACRO;
  1804. goto fail;
  1805. }
  1806. while (nToWrite) {
  1807. uint8_t blockOfCluster = m_vol->blockOfCluster(m_curPosition);
  1808. uint16_t blockOffset = m_curPosition & 0X1FF;
  1809. if (blockOfCluster == 0 && blockOffset == 0) {
  1810. // start of new cluster
  1811. if (m_curCluster != 0) {
  1812. uint32_t next;
  1813. if (!m_vol->fatGet(m_curCluster, &next)) {
  1814. DBG_FAIL_MACRO;
  1815. goto fail;
  1816. }
  1817. if (m_vol->isEOC(next)) {
  1818. // add cluster if at end of chain
  1819. if (!addCluster()) {
  1820. DBG_FAIL_MACRO;
  1821. goto fail;
  1822. }
  1823. } else {
  1824. m_curCluster = next;
  1825. }
  1826. } else {
  1827. if (m_firstCluster == 0) {
  1828. // allocate first cluster of file
  1829. if (!addCluster()) {
  1830. DBG_FAIL_MACRO;
  1831. goto fail;
  1832. }
  1833. } else {
  1834. m_curCluster = m_firstCluster;
  1835. }
  1836. }
  1837. }
  1838. // block for data write
  1839. uint32_t block = m_vol->clusterStartBlock(m_curCluster) + blockOfCluster;
  1840. if (blockOffset != 0 || nToWrite < 512) {
  1841. // partial block - must use cache
  1842. if (blockOffset == 0 && m_curPosition >= m_fileSize) {
  1843. // start of new block don't need to read into cache
  1844. cacheOption = SdVolume::CACHE_RESERVE_FOR_WRITE;
  1845. } else {
  1846. // rewrite part of block
  1847. cacheOption = SdVolume::CACHE_FOR_WRITE;
  1848. }
  1849. pc = m_vol->cacheFetch(block, cacheOption);
  1850. if (!pc) {
  1851. DBG_FAIL_MACRO;
  1852. goto fail;
  1853. }
  1854. // max space in block
  1855. uint16_t space = 512 - blockOffset;
  1856. // lesser of space and amount to write
  1857. n = space < nToWrite ? space : nToWrite;
  1858. uint8_t* dst = pc->data + blockOffset;
  1859. memcpy(dst, src, n);
  1860. // flush cache if all space used.
  1861. if (n == space) {
  1862. if (!m_vol->cacheWriteData()) {
  1863. DBG_FAIL_MACRO;
  1864. goto fail;
  1865. }
  1866. }
  1867. } else if (!USE_MULTI_BLOCK_SD_IO || nToWrite < 1024) {
  1868. // use single block write command
  1869. n = 512;
  1870. if (m_vol->cacheBlockNumber() == block) {
  1871. m_vol->cacheInvalidate();
  1872. }
  1873. if (!m_vol->writeBlock(block, src)) {
  1874. DBG_FAIL_MACRO;
  1875. goto fail;
  1876. }
  1877. } else {
  1878. // use multiple block write command
  1879. uint8_t maxBlocks = m_vol->blocksPerCluster() - blockOfCluster;
  1880. uint8_t nBlock = nToWrite >> 9;
  1881. if (nBlock > maxBlocks) nBlock = maxBlocks;
  1882. n = 512*nBlock;
  1883. if (!m_vol->sdCard()->writeStart(block, nBlock)) {
  1884. DBG_FAIL_MACRO;
  1885. goto fail;
  1886. }
  1887. for (uint8_t b = 0; b < nBlock; b++) {
  1888. // invalidate cache if block is in cache
  1889. if ((block + b) == m_vol->cacheBlockNumber()) {
  1890. m_vol->cacheInvalidate();
  1891. }
  1892. if (!m_vol->sdCard()->writeData(src + 512*b)) {
  1893. DBG_FAIL_MACRO;
  1894. goto fail;
  1895. }
  1896. }
  1897. if (!m_vol->sdCard()->writeStop()) {
  1898. DBG_FAIL_MACRO;
  1899. goto fail;
  1900. }
  1901. }
  1902. m_curPosition += n;
  1903. src += n;
  1904. nToWrite -= n;
  1905. }
  1906. if (m_curPosition > m_fileSize) {
  1907. // update fileSize and insure sync will update dir entry
  1908. m_fileSize = m_curPosition;
  1909. m_flags |= F_FILE_DIR_DIRTY;
  1910. } else if (m_dateTime && nbyte) {
  1911. // insure sync will update modified date and time
  1912. m_flags |= F_FILE_DIR_DIRTY;
  1913. }
  1914. if (m_flags & O_SYNC) {
  1915. if (!sync()) {
  1916. DBG_FAIL_MACRO;
  1917. goto fail;
  1918. }
  1919. }
  1920. return nbyte;
  1921. fail:
  1922. // return for write error
  1923. writeError = true;
  1924. return -1;
  1925. }