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.

991 lines
34KB

  1. /* FatLib Library
  2. * Copyright (C) 2012 by William Greiman
  3. *
  4. * This file is part of the FatLib 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 FatLib Library. If not, see
  18. * <http://www.gnu.org/licenses/>.
  19. */
  20. #ifndef FatFile_h
  21. #define FatFile_h
  22. /**
  23. * \file
  24. * \brief FatFile class
  25. */
  26. // #include <ctype.h>
  27. #include <string.h>
  28. #include <stddef.h>
  29. #include <limits.h>
  30. #include "FatLibConfig.h"
  31. #include "FatApiConstants.h"
  32. #include "FatStructs.h"
  33. #include "FatVolume.h"
  34. class FatFileSystem;
  35. //------------------------------------------------------------------------------
  36. // Stuff to store strings in AVR flash.
  37. #ifdef __AVR__
  38. #include <avr/pgmspace.h>
  39. #else // __AVR__
  40. #ifndef PGM_P
  41. /** pointer to flash for ARM */
  42. #define PGM_P const char*
  43. #endif // PGM_P
  44. #ifndef PSTR
  45. /** store literal string in flash for ARM */
  46. #define PSTR(x) (x)
  47. #endif // PSTR
  48. #ifndef pgm_read_byte
  49. /** read 8-bits from flash for ARM */
  50. #define pgm_read_byte(addr) (*(const unsigned char*)(addr))
  51. #endif // pgm_read_byte
  52. #ifndef pgm_read_word
  53. /** read 16-bits from flash for ARM */
  54. #define pgm_read_word(addr) (*(const uint16_t*)(addr))
  55. #endif // pgm_read_word
  56. #ifndef PROGMEM
  57. /** store in flash for ARM */
  58. #define PROGMEM const
  59. #endif // PROGMEM
  60. #endif // __AVR__
  61. //------------------------------------------------------------------------------
  62. /**
  63. * \struct FatPos_t
  64. * \brief Internal type for file position - do not use in user apps.
  65. */
  66. struct FatPos_t {
  67. /** stream position */
  68. uint32_t position;
  69. /** cluster for position */
  70. uint32_t cluster;
  71. FatPos_t() : position(0), cluster(0) {}
  72. };
  73. //------------------------------------------------------------------------------
  74. /** Expression for path name separator. */
  75. #define isDirSeparator(c) ((c) == '/')
  76. //------------------------------------------------------------------------------
  77. /**
  78. * \struct fname_t
  79. * \brief Internal type for Short File Name - do not use in user apps.
  80. */
  81. struct fname_t {
  82. /** Flags for base and extension character case and LFN. */
  83. uint8_t flags;
  84. /** length of Long File Name */
  85. size_t len;
  86. /** Long File Name start. */
  87. const char* lfn;
  88. /** position for sequence number */
  89. uint8_t seqPos;
  90. /** Short File Name */
  91. uint8_t sfn[11];
  92. };
  93. /** Derived from a LFN with loss or conversion of characters. */
  94. const uint8_t FNAME_FLAG_LOST_CHARS = 0X01;
  95. /** Base-name or extension has mixed case. */
  96. const uint8_t FNAME_FLAG_MIXED_CASE = 0X02;
  97. /** LFN entries are required for file name. */
  98. const uint8_t FNAME_FLAG_NEED_LFN =
  99. FNAME_FLAG_LOST_CHARS | FNAME_FLAG_MIXED_CASE;
  100. /** Filename base-name is all lower case */
  101. const uint8_t FNAME_FLAG_LC_BASE = DIR_NT_LC_BASE;
  102. /** Filename extension is all lower case. */
  103. const uint8_t FNAME_FLAG_LC_EXT = DIR_NT_LC_EXT;
  104. //==============================================================================
  105. /**
  106. * \class FatFile
  107. * \brief Basic file class.
  108. */
  109. class FatFile {
  110. public:
  111. /** Create an instance. */
  112. FatFile() : m_attr(FILE_ATTR_CLOSED), m_error(0) {}
  113. /** Create a file object and open it in the current working directory.
  114. *
  115. * \param[in] path A path with a valid 8.3 DOS name for a file to be opened.
  116. *
  117. * \param[in] oflag Values for \a oflag are constructed by a bitwise-inclusive
  118. * OR of open flags. see FatFile::open(FatFile*, const char*, uint8_t).
  119. */
  120. FatFile(const char* path, uint8_t oflag) {
  121. m_attr = FILE_ATTR_CLOSED;
  122. m_error = 0;
  123. open(path, oflag);
  124. }
  125. #if DESTRUCTOR_CLOSES_FILE
  126. ~FatFile() {
  127. if (isOpen()) {
  128. close();
  129. }
  130. }
  131. #endif // DESTRUCTOR_CLOSES_FILE
  132. #if ENABLE_ARDUINO_FEATURES
  133. /** List directory contents.
  134. *
  135. * \param[in] flags The inclusive OR of
  136. *
  137. * LS_DATE - %Print file modification date
  138. *
  139. * LS_SIZE - %Print file size.
  140. *
  141. * LS_R - Recursive list of subdirectories.
  142. */
  143. void ls(uint8_t flags = 0) {
  144. ls(&Serial, flags);
  145. }
  146. /** %Print a directory date field.
  147. *
  148. * Format is yyyy-mm-dd.
  149. *
  150. * \param[in] fatDate The date field from a directory entry.
  151. */
  152. static void printFatDate(uint16_t fatDate) {
  153. printFatDate(&Serial, fatDate);
  154. }
  155. /** %Print a directory time field.
  156. *
  157. * Format is hh:mm:ss.
  158. *
  159. * \param[in] fatTime The time field from a directory entry.
  160. */
  161. static void printFatTime(uint16_t fatTime) {
  162. printFatTime(&Serial, fatTime);
  163. }
  164. /** Print a file's name.
  165. *
  166. * \return The value true is returned for success and
  167. * the value false is returned for failure.
  168. */
  169. size_t printName() {
  170. return FatFile::printName(&Serial);
  171. }
  172. #endif // ENABLE_ARDUINO_FEATURES
  173. /** \return value of writeError */
  174. bool getWriteError() {
  175. return m_error & WRITE_ERROR;
  176. }
  177. /** Set writeError to zero */
  178. void clearWriteError() {
  179. m_error &= ~WRITE_ERROR;
  180. }
  181. /** Clear all error bits. */
  182. void clearError() {
  183. m_error = 0;
  184. }
  185. /** \return All error bits. */
  186. uint8_t getError() {
  187. return m_error;
  188. }
  189. /** get position for streams
  190. * \param[out] pos struct to receive position
  191. */
  192. void getpos(FatPos_t* pos);
  193. /** set position for streams
  194. * \param[out] pos struct with value for new position
  195. */
  196. void setpos(FatPos_t* pos);
  197. /** \return The number of bytes available from the current position
  198. * to EOF for normal files. Zero is returned for directory files.
  199. */
  200. uint32_t available() {
  201. return isFile() ? fileSize() - curPosition() : 0;
  202. }
  203. /** Close a file and force cached data and directory information
  204. * to be written to the storage device.
  205. *
  206. * \return The value true is returned for success and
  207. * the value false is returned for failure.
  208. */
  209. bool close();
  210. /** Check for contiguous file and return its raw block range.
  211. *
  212. * \param[out] bgnBlock the first block address for the file.
  213. * \param[out] endBlock the last block address for the file.
  214. *
  215. * \return The value true is returned for success and
  216. * the value false is returned for failure.
  217. */
  218. bool contiguousRange(uint32_t* bgnBlock, uint32_t* endBlock);
  219. /** Create and open a new contiguous file of a specified size.
  220. *
  221. * \note This function only supports short DOS 8.3 names.
  222. * See open() for more information.
  223. *
  224. * \param[in] dirFile The directory where the file will be created.
  225. * \param[in] path A path with a valid DOS 8.3 file name.
  226. * \param[in] size The desired file size.
  227. *
  228. * \return The value true is returned for success and
  229. * the value false, is returned for failure.
  230. */
  231. bool createContiguous(FatFile* dirFile,
  232. const char* path, uint32_t size);
  233. /** \return The current cluster number for a file or directory. */
  234. uint32_t curCluster() const {
  235. return m_curCluster;
  236. }
  237. /** \return The current position for a file or directory. */
  238. uint32_t curPosition() const {
  239. return m_curPosition;
  240. }
  241. /** \return Current working directory */
  242. static FatFile* cwd() {
  243. return m_cwd;
  244. }
  245. /** Set the date/time callback function
  246. *
  247. * \param[in] dateTime The user's call back function. The callback
  248. * function is of the form:
  249. *
  250. * \code
  251. * void dateTime(uint16_t* date, uint16_t* time) {
  252. * uint16_t year;
  253. * uint8_t month, day, hour, minute, second;
  254. *
  255. * // User gets date and time from GPS or real-time clock here
  256. *
  257. * // return date using FAT_DATE macro to format fields
  258. * *date = FAT_DATE(year, month, day);
  259. *
  260. * // return time using FAT_TIME macro to format fields
  261. * *time = FAT_TIME(hour, minute, second);
  262. * }
  263. * \endcode
  264. *
  265. * Sets the function that is called when a file is created or when
  266. * a file's directory entry is modified by sync(). All timestamps,
  267. * access, creation, and modify, are set when a file is created.
  268. * sync() maintains the last access date and last modify date/time.
  269. *
  270. * See the timestamp() function.
  271. */
  272. static void dateTimeCallback(
  273. void (*dateTime)(uint16_t* date, uint16_t* time)) {
  274. m_dateTime = dateTime;
  275. }
  276. /** Cancel the date/time callback function. */
  277. static void dateTimeCallbackCancel() {
  278. m_dateTime = 0;
  279. }
  280. /** Return a file's directory entry.
  281. *
  282. * \param[out] dir Location for return of the file's directory entry.
  283. *
  284. * \return The value true is returned for success and
  285. * the value false is returned for failure.
  286. */
  287. bool dirEntry(dir_t* dir);
  288. /**
  289. * \return The index of this file in it's directory.
  290. */
  291. uint16_t dirIndex() {
  292. return m_dirIndex;
  293. }
  294. /** Format the name field of \a dir into the 13 byte array
  295. * \a name in standard 8.3 short name format.
  296. *
  297. * \param[in] dir The directory structure containing the name.
  298. * \param[out] name A 13 byte char array for the formatted name.
  299. * \return length of the name.
  300. */
  301. static uint8_t dirName(const dir_t* dir, char* name);
  302. /** \return The number of bytes allocated to a directory or zero
  303. * if an error occurs.
  304. */
  305. uint32_t dirSize();
  306. /** Dump file in Hex
  307. * \param[in] pr Print stream for list.
  308. * \param[in] pos Start position in file.
  309. * \param[in] n number of locations to dump.
  310. */
  311. void dmpFile(print_t* pr, uint32_t pos, size_t n);
  312. /** Test for the existence of a file in a directory
  313. *
  314. * \param[in] path Path of the file to be tested for.
  315. *
  316. * The calling instance must be an open directory file.
  317. *
  318. * dirFile.exists("TOFIND.TXT") searches for "TOFIND.TXT" in the directory
  319. * dirFile.
  320. *
  321. * \return true if the file exists else false.
  322. */
  323. bool exists(const char* path) {
  324. FatFile file;
  325. return file.open(this, path, O_READ);
  326. }
  327. /**
  328. * Get a string from a file.
  329. *
  330. * fgets() reads bytes from a file into the array pointed to by \a str, until
  331. * \a num - 1 bytes are read, or a delimiter is read and transferred to \a str,
  332. * or end-of-file is encountered. The string is then terminated
  333. * with a null byte.
  334. *
  335. * fgets() deletes CR, '\\r', from the string. This insures only a '\\n'
  336. * terminates the string for Windows text files which use CRLF for newline.
  337. *
  338. * \param[out] str Pointer to the array where the string is stored.
  339. * \param[in] num Maximum number of characters to be read
  340. * (including the final null byte). Usually the length
  341. * of the array \a str is used.
  342. * \param[in] delim Optional set of delimiters. The default is "\n".
  343. *
  344. * \return For success fgets() returns the length of the string in \a str.
  345. * If no data is read, fgets() returns zero for EOF or -1 if an error occurred.
  346. */
  347. int16_t fgets(char* str, int16_t num, char* delim = 0);
  348. /** \return The total number of bytes in a file. */
  349. uint32_t fileSize() const {
  350. return m_fileSize;
  351. }
  352. /** \return The first cluster number for a file or directory. */
  353. uint32_t firstCluster() const {
  354. return m_firstCluster;
  355. }
  356. /**
  357. * Get a file's name followed by a zero byte.
  358. *
  359. * \param[out] name An array of characters for the file's name.
  360. * \param[in] size The size of the array in bytes. The array
  361. * must be at least 13 bytes long. The file's name will be
  362. * truncated if the file's name is too long.
  363. * \return The value true, is returned for success and
  364. * the value false, is returned for failure.
  365. */
  366. bool getName(char* name, size_t size);
  367. /**
  368. * Get a file's Short File Name followed by a zero byte.
  369. *
  370. * \param[out] name An array of characters for the file's name.
  371. * The array must be at least 13 bytes long.
  372. * \return The value true, is returned for success and
  373. * the value false, is returned for failure.
  374. */
  375. bool getSFN(char* name);
  376. /** \return True if this is a directory else false. */
  377. bool isDir() const {
  378. return m_attr & FILE_ATTR_DIR;
  379. }
  380. /** \return True if this is a normal file else false. */
  381. bool isFile() const {
  382. return m_attr & FILE_ATTR_FILE;
  383. }
  384. /** \return True if this is a hidden file else false. */
  385. bool isHidden() const {
  386. return m_attr & FILE_ATTR_HIDDEN;
  387. }
  388. /** \return true if this file has a Long File Name. */
  389. bool isLFN() const {
  390. return m_lfnOrd;
  391. }
  392. /** \return True if this is an open file/directory else false. */
  393. bool isOpen() const {
  394. return m_attr;
  395. }
  396. /** \return True if this is the root directory. */
  397. bool isRoot() const {
  398. return m_attr & FILE_ATTR_ROOT;
  399. }
  400. /** \return True if this is the FAT32 root directory. */
  401. bool isRoot32() const {
  402. return m_attr & FILE_ATTR_ROOT32;
  403. }
  404. /** \return True if this is the FAT12 of FAT16 root directory. */
  405. bool isRootFixed() const {
  406. return m_attr & FILE_ATTR_ROOT_FIXED;
  407. }
  408. /** \return True if file is read-only */
  409. bool isReadOnly() const {
  410. return m_attr & FILE_ATTR_READ_ONLY;
  411. }
  412. /** \return True if this is a subdirectory else false. */
  413. bool isSubDir() const {
  414. return m_attr & FILE_ATTR_SUBDIR;
  415. }
  416. /** \return True if this is a system file else false. */
  417. bool isSystem() const {
  418. return m_attr & FILE_ATTR_SYSTEM;
  419. }
  420. /** Check for a legal 8.3 character.
  421. * \param[in] c Character to be checked.
  422. * \return true for a legal 8.3 character else false.
  423. */
  424. static bool legal83Char(uint8_t c) {
  425. if (c == '"' || c == '|') {
  426. return false;
  427. }
  428. // *+,./
  429. if (0X2A <= c && c <= 0X2F && c != 0X2D) {
  430. return false;
  431. }
  432. // :;<=>?
  433. if (0X3A <= c && c <= 0X3F) {
  434. return false;
  435. }
  436. // [\]
  437. if (0X5B <= c && c <= 0X5D) {
  438. return false;
  439. }
  440. return 0X20 < c && c < 0X7F;
  441. }
  442. /** List directory contents.
  443. *
  444. * \param[in] pr Print stream for list.
  445. *
  446. * \param[in] flags The inclusive OR of
  447. *
  448. * LS_DATE - %Print file modification date
  449. *
  450. * LS_SIZE - %Print file size.
  451. *
  452. * LS_R - Recursive list of subdirectories.
  453. *
  454. * \param[in] indent Amount of space before file name. Used for recursive
  455. * list to indicate subdirectory level.
  456. */
  457. void ls(print_t* pr, uint8_t flags = 0, uint8_t indent = 0);
  458. /** Make a new directory.
  459. *
  460. * \param[in] dir An open FatFile instance for the directory that will
  461. * contain the new directory.
  462. *
  463. * \param[in] path A path with a valid 8.3 DOS name for the new directory.
  464. *
  465. * \param[in] pFlag Create missing parent directories if true.
  466. *
  467. * \return The value true is returned for success and
  468. * the value false is returned for failure.
  469. */
  470. bool mkdir(FatFile* dir, const char* path, bool pFlag = true);
  471. /** Open a file in the volume working directory of a FatFileSystem.
  472. *
  473. * \param[in] fs File System where the file is located.
  474. *
  475. * \param[in] path with a valid 8.3 DOS name for a file to be opened.
  476. *
  477. * \param[in] oflag bitwise-inclusive OR of open mode flags.
  478. * See see FatFile::open(FatFile*, const char*, uint8_t).
  479. *
  480. * \return The value true is returned for success and
  481. * the value false is returned for failure.
  482. */
  483. bool open(FatFileSystem* fs, const char* path, uint8_t oflag);
  484. /** Open a file by index.
  485. *
  486. * \param[in] dirFile An open FatFile instance for the directory.
  487. *
  488. * \param[in] index The \a index of the directory entry for the file to be
  489. * opened. The value for \a index is (directory file position)/32.
  490. *
  491. * \param[in] oflag bitwise-inclusive OR of open mode flags.
  492. * See see FatFile::open(FatFile*, const char*, uint8_t).
  493. *
  494. * See open() by path for definition of flags.
  495. * \return true for success or false for failure.
  496. */
  497. bool open(FatFile* dirFile, uint16_t index, uint8_t oflag);
  498. /** Open a file or directory by name.
  499. *
  500. * \param[in] dirFile An open FatFile instance for the directory containing
  501. * the file to be opened.
  502. *
  503. * \param[in] path A path with a valid 8.3 DOS name for a file to be opened.
  504. *
  505. * \param[in] oflag Values for \a oflag are constructed by a
  506. * bitwise-inclusive OR of flags from the following list
  507. *
  508. * O_READ - Open for reading.
  509. *
  510. * O_RDONLY - Same as O_READ.
  511. *
  512. * O_WRITE - Open for writing.
  513. *
  514. * O_WRONLY - Same as O_WRITE.
  515. *
  516. * O_RDWR - Open for reading and writing.
  517. *
  518. * O_APPEND - If set, the file offset shall be set to the end of the
  519. * file prior to each write.
  520. *
  521. * O_AT_END - Set the initial position at the end of the file.
  522. *
  523. * O_CREAT - If the file exists, this flag has no effect except as noted
  524. * under O_EXCL below. Otherwise, the file shall be created
  525. *
  526. * O_EXCL - If O_CREAT and O_EXCL are set, open() shall fail if the file exists.
  527. *
  528. * O_SYNC - Call sync() after each write. This flag should not be used with
  529. * write(uint8_t) or any functions do character at a time writes since sync()
  530. * will be called after each byte.
  531. *
  532. * O_TRUNC - If the file exists and is a regular file, and the file is
  533. * successfully opened and is not read only, its length shall be truncated to 0.
  534. *
  535. * WARNING: A given file must not be opened by more than one FatFile object
  536. * or file corruption may occur.
  537. *
  538. * \note Directory files must be opened read only. Write and truncation is
  539. * not allowed for directory files.
  540. *
  541. * \return The value true is returned for success and
  542. * the value false is returned for failure.
  543. */
  544. bool open(FatFile* dirFile, const char* path, uint8_t oflag);
  545. /** Open a file in the current working directory.
  546. *
  547. * \param[in] path A path with a valid 8.3 DOS name for a file to be opened.
  548. *
  549. * \param[in] oflag bitwise-inclusive OR of open mode flags.
  550. * See see FatFile::open(FatFile*, const char*, uint8_t).
  551. *
  552. * \return The value true is returned for success and
  553. * the value false is returned for failure.
  554. */
  555. bool open(const char* path, uint8_t oflag = O_READ) {
  556. return open(m_cwd, path, oflag);
  557. }
  558. /** Open the next file or subdirectory in a directory.
  559. *
  560. * \param[in] dirFile An open FatFile instance for the directory
  561. * containing the file to be opened.
  562. *
  563. * \param[in] oflag bitwise-inclusive OR of open mode flags.
  564. * See see FatFile::open(FatFile*, const char*, uint8_t).
  565. *
  566. * \return true for success or false for failure.
  567. */
  568. bool openNext(FatFile* dirFile, uint8_t oflag = O_READ);
  569. /** Open a volume's root directory.
  570. *
  571. * \param[in] vol The FAT volume containing the root directory to be opened.
  572. *
  573. * \return The value true is returned for success and
  574. * the value false is returned for failure.
  575. */
  576. bool openRoot(FatVolume* vol);
  577. /** Return the next available byte without consuming it.
  578. *
  579. * \return The byte if no error and not at eof else -1;
  580. */
  581. int peek();
  582. /** Print a file's creation date and time
  583. *
  584. * \param[in] pr Print stream for output.
  585. *
  586. * \return The value true is returned for success and
  587. * the value false is returned for failure.
  588. */
  589. bool printCreateDateTime(print_t* pr);
  590. /** %Print a directory date field.
  591. *
  592. * Format is yyyy-mm-dd.
  593. *
  594. * \param[in] pr Print stream for output.
  595. * \param[in] fatDate The date field from a directory entry.
  596. */
  597. static void printFatDate(print_t* pr, uint16_t fatDate);
  598. /** %Print a directory time field.
  599. *
  600. * Format is hh:mm:ss.
  601. *
  602. * \param[in] pr Print stream for output.
  603. * \param[in] fatTime The time field from a directory entry.
  604. */
  605. static void printFatTime(print_t* pr, uint16_t fatTime);
  606. /** Print a number followed by a field terminator.
  607. * \param[in] value The number to be printed.
  608. * \param[in] term The field terminator. Use '\\n' for CR LF.
  609. * \param[in] prec Number of digits after decimal point.
  610. * \return The number of bytes written or -1 if an error occurs.
  611. */
  612. int printField(float value, char term, uint8_t prec = 2);
  613. /** Print a number followed by a field terminator.
  614. * \param[in] value The number to be printed.
  615. * \param[in] term The field terminator. Use '\\n' for CR LF.
  616. * \return The number of bytes written or -1 if an error occurs.
  617. */
  618. int printField(int16_t value, char term);
  619. /** Print a number followed by a field terminator.
  620. * \param[in] value The number to be printed.
  621. * \param[in] term The field terminator. Use '\\n' for CR LF.
  622. * \return The number of bytes written or -1 if an error occurs.
  623. */
  624. int printField(uint16_t value, char term);
  625. /** Print a number followed by a field terminator.
  626. * \param[in] value The number to be printed.
  627. * \param[in] term The field terminator. Use '\\n' for CR LF.
  628. * \return The number of bytes written or -1 if an error occurs.
  629. */
  630. int printField(int32_t value, char term);
  631. /** Print a number followed by a field terminator.
  632. * \param[in] value The number to be printed.
  633. * \param[in] term The field terminator. Use '\\n' for CR LF.
  634. * \return The number of bytes written or -1 if an error occurs.
  635. */
  636. int printField(uint32_t value, char term);
  637. /** Print a file's modify date and time
  638. *
  639. * \param[in] pr Print stream for output.
  640. *
  641. * \return The value true is returned for success and
  642. * the value false is returned for failure.
  643. */
  644. bool printModifyDateTime(print_t* pr);
  645. /** Print a file's name
  646. *
  647. * \param[in] pr Print stream for output.
  648. *
  649. * \return The value true is returned for success and
  650. * the value false is returned for failure.
  651. */
  652. size_t printName(print_t* pr);
  653. /** Print a file's size.
  654. *
  655. * \param[in] pr Print stream for output.
  656. *
  657. * \return The number of characters printed is returned
  658. * for success and zero is returned for failure.
  659. */
  660. size_t printFileSize(print_t* pr);
  661. /** Print a file's Short File Name.
  662. *
  663. * \param[in] pr Print stream for output.
  664. *
  665. * \return The number of characters printed is returned
  666. * for success and zero is returned for failure.
  667. */
  668. size_t printSFN(print_t* pr);
  669. /** Read the next byte from a file.
  670. *
  671. * \return For success read returns the next byte in the file as an int.
  672. * If an error occurs or end of file is reached -1 is returned.
  673. */
  674. int read() {
  675. uint8_t b;
  676. return read(&b, 1) == 1 ? b : -1;
  677. }
  678. /** Read data from a file starting at the current position.
  679. *
  680. * \param[out] buf Pointer to the location that will receive the data.
  681. *
  682. * \param[in] nbyte Maximum number of bytes to read.
  683. *
  684. * \return For success read() returns the number of bytes read.
  685. * A value less than \a nbyte, including zero, will be returned
  686. * if end of file is reached.
  687. * If an error occurs, read() returns -1. Possible errors include
  688. * read() called before a file has been opened, corrupt file system
  689. * or an I/O error occurred.
  690. */
  691. int read(void* buf, size_t nbyte);
  692. /** Read the next directory entry from a directory file.
  693. *
  694. * \param[out] dir The dir_t struct that will receive the data.
  695. *
  696. * \return For success readDir() returns the number of bytes read.
  697. * A value of zero will be returned if end of file is reached.
  698. * If an error occurs, readDir() returns -1. Possible errors include
  699. * readDir() called before a directory has been opened, this is not
  700. * a directory file or an I/O error occurred.
  701. */
  702. int8_t readDir(dir_t* dir);
  703. /** Remove a file.
  704. *
  705. * The directory entry and all data for the file are deleted.
  706. *
  707. * \note This function should not be used to delete the 8.3 version of a
  708. * file that has a long name. For example if a file has the long name
  709. * "New Text Document.txt" you should not delete the 8.3 name "NEWTEX~1.TXT".
  710. *
  711. * \return The value true is returned for success and
  712. * the value false is returned for failure.
  713. */
  714. bool remove();
  715. /** Remove a file.
  716. *
  717. * The directory entry and all data for the file are deleted.
  718. *
  719. * \param[in] dirFile The directory that contains the file.
  720. * \param[in] path Path for the file to be removed.
  721. *
  722. * \note This function should not be used to delete the 8.3 version of a
  723. * file that has a long name. For example if a file has the long name
  724. * "New Text Document.txt" you should not delete the 8.3 name "NEWTEX~1.TXT".
  725. *
  726. * \return The value true is returned for success and
  727. * the value false is returned for failure.
  728. */
  729. static bool remove(FatFile* dirFile, const char* path);
  730. /** Set the file's current position to zero. */
  731. void rewind() {
  732. seekSet(0);
  733. }
  734. /** Rename a file or subdirectory.
  735. *
  736. * \param[in] dirFile Directory for the new path.
  737. * \param[in] newPath New path name for the file/directory.
  738. *
  739. * \return The value true is returned for success and
  740. * the value false is returned for failure.
  741. */
  742. bool rename(FatFile* dirFile, const char* newPath);
  743. /** Remove a directory file.
  744. *
  745. * The directory file will be removed only if it is empty and is not the
  746. * root directory. rmdir() follows DOS and Windows and ignores the
  747. * read-only attribute for the directory.
  748. *
  749. * \note This function should not be used to delete the 8.3 version of a
  750. * directory that has a long name. For example if a directory has the
  751. * long name "New folder" you should not delete the 8.3 name "NEWFOL~1".
  752. *
  753. * \return The value true is returned for success and
  754. * the value false is returned for failure.
  755. */
  756. bool rmdir();
  757. /** Recursively delete a directory and all contained files.
  758. *
  759. * This is like the Unix/Linux 'rm -rf *' if called with the root directory
  760. * hence the name.
  761. *
  762. * Warning - This will remove all contents of the directory including
  763. * subdirectories. The directory will then be removed if it is not root.
  764. * The read-only attribute for files will be ignored.
  765. *
  766. * \note This function should not be used to delete the 8.3 version of
  767. * a directory that has a long name. See remove() and rmdir().
  768. *
  769. * \return The value true is returned for success and
  770. * the value false is returned for failure.
  771. */
  772. bool rmRfStar();
  773. /** Set the files position to current position + \a pos. See seekSet().
  774. * \param[in] offset The new position in bytes from the current position.
  775. * \return true for success or false for failure.
  776. */
  777. bool seekCur(int32_t offset) {
  778. return seekSet(m_curPosition + offset);
  779. }
  780. /** Set the files position to end-of-file + \a offset. See seekSet().
  781. * Can't be used for directory files since file size is not defined.
  782. * \param[in] offset The new position in bytes from end-of-file.
  783. * \return true for success or false for failure.
  784. */
  785. bool seekEnd(int32_t offset = 0) {
  786. return isFile() ? seekSet(m_fileSize + offset) : false;
  787. }
  788. /** Sets a file's position.
  789. *
  790. * \param[in] pos The new position in bytes from the beginning of the file.
  791. *
  792. * \return The value true is returned for success and
  793. * the value false is returned for failure.
  794. */
  795. bool seekSet(uint32_t pos);
  796. /** Set the current working directory.
  797. *
  798. * \param[in] dir New current working directory.
  799. *
  800. * \return true for success else false.
  801. */
  802. static bool setCwd(FatFile* dir) {
  803. if (!dir->isDir()) {
  804. return false;
  805. }
  806. m_cwd = dir;
  807. return true;
  808. }
  809. /** The sync() call causes all modified data and directory fields
  810. * to be written to the storage device.
  811. *
  812. * \return The value true is returned for success and
  813. * the value false is returned for failure.
  814. */
  815. bool sync();
  816. /** Copy a file's timestamps
  817. *
  818. * \param[in] file File to copy timestamps from.
  819. *
  820. * \note
  821. * Modify and access timestamps may be overwritten if a date time callback
  822. * function has been set by dateTimeCallback().
  823. *
  824. * \return The value true is returned for success and
  825. * the value false is returned for failure.
  826. */
  827. bool timestamp(FatFile* file);
  828. /** Set a file's timestamps in its directory entry.
  829. *
  830. * \param[in] flags Values for \a flags are constructed by a bitwise-inclusive
  831. * OR of flags from the following list
  832. *
  833. * T_ACCESS - Set the file's last access date.
  834. *
  835. * T_CREATE - Set the file's creation date and time.
  836. *
  837. * T_WRITE - Set the file's last write/modification date and time.
  838. *
  839. * \param[in] year Valid range 1980 - 2107 inclusive.
  840. *
  841. * \param[in] month Valid range 1 - 12 inclusive.
  842. *
  843. * \param[in] day Valid range 1 - 31 inclusive.
  844. *
  845. * \param[in] hour Valid range 0 - 23 inclusive.
  846. *
  847. * \param[in] minute Valid range 0 - 59 inclusive.
  848. *
  849. * \param[in] second Valid range 0 - 59 inclusive
  850. *
  851. * \note It is possible to set an invalid date since there is no check for
  852. * the number of days in a month.
  853. *
  854. * \note
  855. * Modify and access timestamps may be overwritten if a date time callback
  856. * function has been set by dateTimeCallback().
  857. *
  858. * \return The value true is returned for success and
  859. * the value false is returned for failure.
  860. */
  861. bool timestamp(uint8_t flags, uint16_t year, uint8_t month, uint8_t day,
  862. uint8_t hour, uint8_t minute, uint8_t second);
  863. /** Type of file. You should use isFile() or isDir() instead of fileType()
  864. * if possible.
  865. *
  866. * \return The file or directory type.
  867. */
  868. uint8_t fileAttr() const {
  869. return m_attr;
  870. }
  871. /** Truncate a file to a specified length. The current file position
  872. * will be maintained if it is less than or equal to \a length otherwise
  873. * it will be set to end of file.
  874. *
  875. * \param[in] length The desired length for the file.
  876. *
  877. * \return The value true is returned for success and
  878. * the value false is returned for failure.
  879. */
  880. bool truncate(uint32_t length);
  881. /** \return FatVolume that contains this file. */
  882. FatVolume* volume() const {
  883. return m_vol;
  884. }
  885. /** Write a string to a file. Used by the Arduino Print class.
  886. * \param[in] str Pointer to the string.
  887. * Use getWriteError to check for errors.
  888. * \return count of characters written for success or -1 for failure.
  889. */
  890. int write(const char* str) {
  891. return write(str, strlen(str));
  892. }
  893. /** Write a single byte.
  894. * \param[in] b The byte to be written.
  895. * \return +1 for success or -1 for failure.
  896. */
  897. int write(uint8_t b) {
  898. return write(&b, 1);
  899. }
  900. /** Write data to an open file.
  901. *
  902. * \note Data is moved to the cache but may not be written to the
  903. * storage device until sync() is called.
  904. *
  905. * \param[in] buf Pointer to the location of the data to be written.
  906. *
  907. * \param[in] nbyte Number of bytes to write.
  908. *
  909. * \return For success write() returns the number of bytes written, always
  910. * \a nbyte. If an error occurs, write() returns -1. Possible errors
  911. * include write() is called before a file has been opened, write is called
  912. * for a read-only file, device is full, a corrupt file system or an I/O error.
  913. *
  914. */
  915. int write(const void* buf, size_t nbyte);
  916. //------------------------------------------------------------------------------
  917. private:
  918. /** This file has not been opened. */
  919. static const uint8_t FILE_ATTR_CLOSED = 0;
  920. /** File is read-only. */
  921. static const uint8_t FILE_ATTR_READ_ONLY = DIR_ATT_READ_ONLY;
  922. /** File should be hidden in directory listings. */
  923. static const uint8_t FILE_ATTR_HIDDEN = DIR_ATT_HIDDEN;
  924. /** Entry is for a system file. */
  925. static const uint8_t FILE_ATTR_SYSTEM = DIR_ATT_SYSTEM;
  926. /** Entry for normal data file */
  927. static const uint8_t FILE_ATTR_FILE = 0X08;
  928. /** Entry is for a subdirectory */
  929. static const uint8_t FILE_ATTR_SUBDIR = DIR_ATT_DIRECTORY;
  930. /** A FAT12 or FAT16 root directory */
  931. static const uint8_t FILE_ATTR_ROOT_FIXED = 0X20;
  932. /** A FAT32 root directory */
  933. static const uint8_t FILE_ATTR_ROOT32 = 0X40;
  934. /** Entry is for root. */
  935. static const uint8_t FILE_ATTR_ROOT = FILE_ATTR_ROOT_FIXED | FILE_ATTR_ROOT32;
  936. /** Directory type bits */
  937. static const uint8_t FILE_ATTR_DIR = FILE_ATTR_SUBDIR | FILE_ATTR_ROOT;
  938. /** Attributes to copy from directory entry */
  939. static const uint8_t FILE_ATTR_COPY = DIR_ATT_READ_ONLY | DIR_ATT_HIDDEN |
  940. DIR_ATT_SYSTEM | DIR_ATT_DIRECTORY;
  941. /** experimental don't use */
  942. bool openParent(FatFile* dir);
  943. // private functions
  944. bool addCluster();
  945. bool addDirCluster();
  946. dir_t* cacheDirEntry(uint8_t action);
  947. static uint8_t lfnChecksum(uint8_t* name);
  948. bool lfnUniqueSfn(fname_t* fname);
  949. bool openCluster(FatFile* file);
  950. static bool parsePathName(const char* str, fname_t* fname, const char** ptr);
  951. bool mkdir(FatFile* parent, fname_t* fname);
  952. bool open(FatFile* dirFile, fname_t* fname, uint8_t oflag);
  953. bool openCachedEntry(FatFile* dirFile, uint16_t cacheIndex, uint8_t oflag,
  954. uint8_t lfnOrd);
  955. bool readLBN(uint32_t* lbn);
  956. dir_t* readDirCache(bool skipReadOk = false);
  957. bool setDirSize();
  958. // bits defined in m_flags
  959. // should be 0X0F
  960. static uint8_t const F_OFLAG = (O_ACCMODE | O_APPEND | O_SYNC);
  961. // sync of directory entry required
  962. static uint8_t const F_FILE_DIR_DIRTY = 0X80;
  963. // global pointer to cwd dir
  964. static FatFile* m_cwd;
  965. // data time callback function
  966. static void (*m_dateTime)(uint16_t* date, uint16_t* time);
  967. // private data
  968. static const uint8_t WRITE_ERROR = 0X1;
  969. static const uint8_t READ_ERROR = 0X2;
  970. uint8_t m_attr; // File attributes
  971. uint8_t m_error; // Error bits.
  972. uint8_t m_flags; // See above for definition of m_flags bits
  973. uint8_t m_lfnOrd;
  974. uint16_t m_dirIndex; // index of directory entry in dir file
  975. FatVolume* m_vol; // volume where file is located
  976. uint32_t m_dirCluster;
  977. uint32_t m_curCluster; // cluster for current file position
  978. uint32_t m_curPosition; // current file position
  979. uint32_t m_dirBlock; // block for this files directory entry
  980. uint32_t m_fileSize; // file size in bytes
  981. uint32_t m_firstCluster; // first cluster of file
  982. };
  983. #endif // FatFile_h