FatFile.h 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070
  1. /**
  2. * Copyright (c) 2011-2021 Bill Greiman
  3. * This file is part of the SdFat library for SD memory cards.
  4. *
  5. * MIT License
  6. *
  7. * Permission is hereby granted, free of charge, to any person obtaining a
  8. * copy of this software and associated documentation files (the "Software"),
  9. * to deal in the Software without restriction, including without limitation
  10. * the rights to use, copy, modify, merge, publish, distribute, sublicense,
  11. * and/or sell copies of the Software, and to permit persons to whom the
  12. * Software is furnished to do so, subject to the following conditions:
  13. *
  14. * The above copyright notice and this permission notice shall be included
  15. * in all copies or substantial portions of the Software.
  16. *
  17. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  18. * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  19. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  20. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  21. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  22. * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  23. * DEALINGS IN THE SOFTWARE.
  24. */
  25. #ifndef FatFile_h
  26. #define FatFile_h
  27. /**
  28. * \file
  29. * \brief FatFile class
  30. */
  31. #include <string.h>
  32. #include <stddef.h>
  33. #include <limits.h>
  34. #include "../common/FmtNumber.h"
  35. #include "../common/FsApiConstants.h"
  36. #include "../common/FsDateTime.h"
  37. #include "../common/FsName.h"
  38. #include "FatPartition.h"
  39. class FatVolume;
  40. //------------------------------------------------------------------------------
  41. // Stuff to store strings in AVR flash.
  42. #ifdef __AVR__
  43. #include <avr/pgmspace.h>
  44. #else // __AVR__
  45. #ifndef PSTR
  46. /** store literal string in flash for ARM */
  47. #define PSTR(x) (x)
  48. #endif // PSTR
  49. #ifndef pgm_read_byte
  50. /** read 8-bits from flash for ARM */
  51. #define pgm_read_byte(addr) (*(const unsigned char*)(addr))
  52. #endif // pgm_read_byte
  53. #ifndef pgm_read_word
  54. /** read 16-bits from flash for ARM */
  55. #define pgm_read_word(addr) (*(const uint16_t*)(addr))
  56. #endif // pgm_read_word
  57. #ifndef PROGMEM
  58. /** store in flash for ARM */
  59. #define PROGMEM
  60. #endif // PROGMEM
  61. #endif // __AVR__
  62. //------------------------------------------------------------------------------
  63. /**
  64. * \struct FatPos_t
  65. * \brief Internal type for file position - do not use in user apps.
  66. */
  67. struct FatPos_t {
  68. /** stream position */
  69. uint32_t position;
  70. /** cluster for position */
  71. uint32_t cluster;
  72. };
  73. //------------------------------------------------------------------------------
  74. /** Expression for path name separator. */
  75. #define isDirSeparator(c) ((c) == '/')
  76. //------------------------------------------------------------------------------
  77. /**
  78. * \class FatLfn_t
  79. * \brief Internal type for Long File Name - do not use in user apps.
  80. */
  81. class FatLfn_t : public FsName {
  82. public:
  83. /** UTF-16 length of Long File Name */
  84. size_t len;
  85. /** Position for sequence number. */
  86. uint8_t seqPos;
  87. /** Flags for base and extension character case and LFN. */
  88. uint8_t flags;
  89. /** Short File Name */
  90. uint8_t sfn[11];
  91. };
  92. /**
  93. * \class FatSfn_t
  94. * \brief Internal type for Short 8.3 File Name - do not use in user apps.
  95. */
  96. class FatSfn_t {
  97. public:
  98. /** Flags for base and extension character case and LFN. */
  99. uint8_t flags;
  100. /** Short File Name */
  101. uint8_t sfn[11];
  102. };
  103. #if USE_LONG_FILE_NAMES
  104. /** Internal class for file names */
  105. typedef FatLfn_t FatName_t;
  106. #else // USE_LONG_FILE_NAMES
  107. /** Internal class for file names */
  108. typedef FatSfn_t FatName_t;
  109. #endif // USE_LONG_FILE_NAMES
  110. /** Derived from a LFN with loss or conversion of characters. */
  111. const uint8_t FNAME_FLAG_LOST_CHARS = 0X01;
  112. /** Base-name or extension has mixed case. */
  113. const uint8_t FNAME_FLAG_MIXED_CASE = 0X02;
  114. /** LFN entries are required for file name. */
  115. const uint8_t FNAME_FLAG_NEED_LFN =
  116. FNAME_FLAG_LOST_CHARS | FNAME_FLAG_MIXED_CASE;
  117. /** Filename base-name is all lower case */
  118. const uint8_t FNAME_FLAG_LC_BASE = FAT_CASE_LC_BASE;
  119. /** Filename extension is all lower case. */
  120. const uint8_t FNAME_FLAG_LC_EXT = FAT_CASE_LC_EXT;
  121. #if FNAME_FLAG_NEED_LFN & (FAT_CASE_LC_BASE || FAT_CASE_LC_EXT)
  122. #error FNAME_FLAG_NEED_LFN & (FAT_CASE_LC_BASE || FAT_CASE_LC_EXT)
  123. #endif // FNAME_FLAG_NEED_LFN & (FAT_CASE_LC_BASE || FAT_CASE_LC_EXT)
  124. //==============================================================================
  125. /**
  126. * \class FatFile
  127. * \brief Basic file class.
  128. */
  129. class FatFile {
  130. public:
  131. /** Create an instance. */
  132. FatFile() {}
  133. /** Create a file object and open it in the current working directory.
  134. *
  135. * \param[in] path A path for a file to be opened.
  136. *
  137. * \param[in] oflag Values for \a oflag are constructed by a bitwise-inclusive
  138. * OR of open flags. see FatFile::open(FatFile*, const char*, uint8_t).
  139. */
  140. FatFile(const char* path, oflag_t oflag) {
  141. open(path, oflag);
  142. }
  143. #if DESTRUCTOR_CLOSES_FILE
  144. /** Destructor */
  145. ~FatFile() {
  146. if (isOpen()) {
  147. close();
  148. }
  149. }
  150. #endif // DESTRUCTOR_CLOSES_FILE
  151. /** The parenthesis operator.
  152. *
  153. * \return true if a file is open.
  154. */
  155. operator bool() const {return isOpen();}
  156. /** \return The number of bytes available from the current position
  157. * to EOF for normal files. INT_MAX is returned for very large files.
  158. *
  159. * available32() is recomended for very large files.
  160. *
  161. * Zero is returned for directory files.
  162. *
  163. */
  164. int available() const {
  165. uint32_t n = available32();
  166. return n > INT_MAX ? INT_MAX : n;
  167. }
  168. /** \return The number of bytes available from the current position
  169. * to EOF for normal files. Zero is returned for directory files.
  170. */
  171. uint32_t available32() const {
  172. return isFile() ? fileSize() - curPosition() : 0;
  173. }
  174. /** Clear all error bits. */
  175. void clearError() {
  176. m_error = 0;
  177. }
  178. /** Set writeError to zero */
  179. void clearWriteError() {
  180. m_error &= ~WRITE_ERROR;
  181. }
  182. /** Close a file and force cached data and directory information
  183. * to be written to the storage device.
  184. *
  185. * \return true for success or false for failure.
  186. */
  187. bool close();
  188. /** Check for contiguous file and return its raw sector range.
  189. *
  190. * \param[out] bgnSector the first sector address for the file.
  191. * \param[out] endSector the last sector address for the file.
  192. *
  193. * Set the contiguous flag if the file is contiguous.
  194. * The parameters may be nullptr to only set the flag.
  195. * \return true for success or false for failure.
  196. */
  197. bool contiguousRange(uint32_t* bgnSector, uint32_t* endSector);
  198. /** Create and open a new contiguous file of a specified size.
  199. *
  200. * \param[in] dirFile The directory where the file will be created.
  201. * \param[in] path A path with a valid file name.
  202. * \param[in] size The desired file size.
  203. *
  204. * \return true for success or false for failure.
  205. */
  206. bool createContiguous(FatFile* dirFile,
  207. const char* path, uint32_t size);
  208. /** Create and open a new contiguous file of a specified size.
  209. *
  210. * \param[in] path A path with a valid file name.
  211. * \param[in] size The desired file size.
  212. *
  213. * \return true for success or false for failure.
  214. */
  215. bool createContiguous(const char* path, uint32_t size);
  216. /** \return The current cluster number for a file or directory. */
  217. uint32_t curCluster() const {return m_curCluster;}
  218. /** \return The current position for a file or directory. */
  219. uint32_t curPosition() const {return m_curPosition;}
  220. /** Return a file's directory entry.
  221. *
  222. * \param[out] dir Location for return of the file's directory entry.
  223. *
  224. * \return true for success or false for failure.
  225. */
  226. bool dirEntry(DirFat_t* dir);
  227. /** \return Directory entry index. */
  228. uint16_t dirIndex() const {return m_dirIndex;}
  229. /** \return The number of bytes allocated to a directory or zero
  230. * if an error occurs.
  231. */
  232. uint32_t dirSize();
  233. /** Dump file in Hex
  234. * \param[in] pr Print stream for list.
  235. * \param[in] pos Start position in file.
  236. * \param[in] n number of locations to dump.
  237. */
  238. void dmpFile(print_t* pr, uint32_t pos, size_t n);
  239. /** Test for the existence of a file in a directory
  240. *
  241. * \param[in] path Path of the file to be tested for.
  242. *
  243. * The calling instance must be an open directory file.
  244. *
  245. * dirFile.exists("TOFIND.TXT") searches for "TOFIND.TXT" in the directory
  246. * dirFile.
  247. *
  248. * \return True if the file exists.
  249. */
  250. bool exists(const char* path) {
  251. FatFile file;
  252. return file.open(this, path, O_RDONLY);
  253. }
  254. /** get position for streams
  255. * \param[out] pos struct to receive position
  256. */
  257. void fgetpos(fspos_t* pos) const;
  258. /**
  259. * Get a string from a file.
  260. *
  261. * fgets() reads bytes from a file into the array pointed to by \a str, until
  262. * \a num - 1 bytes are read, or a delimiter is read and transferred to
  263. * \a str, or end-of-file is encountered. The string is then terminated
  264. * with a null byte.
  265. *
  266. * fgets() deletes CR, '\\r', from the string. This insures only a '\\n'
  267. * terminates the string for Windows text files which use CRLF for newline.
  268. *
  269. * \param[out] str Pointer to the array where the string is stored.
  270. * \param[in] num Maximum number of characters to be read
  271. * (including the final null byte). Usually the length
  272. * of the array \a str is used.
  273. * \param[in] delim Optional set of delimiters. The default is "\n".
  274. *
  275. * \return For success fgets() returns the length of the string in \a str.
  276. * If no data is read, fgets() returns zero for EOF or -1 if an error
  277. * occurred.
  278. */
  279. int fgets(char* str, int num, char* delim = nullptr);
  280. /** \return The total number of bytes in a file. */
  281. uint32_t fileSize() const {return m_fileSize;}
  282. /** \return first sector of file or zero for empty file. */
  283. uint32_t firstBlock() const {return firstSector();}
  284. /** \return Address of first sector or zero for empty file. */
  285. uint32_t firstSector() const;
  286. /** Arduino name for sync() */
  287. void flush() {sync();}
  288. /** set position for streams
  289. * \param[in] pos struct with value for new position
  290. */
  291. void fsetpos(const fspos_t* pos);
  292. /** Get a file's access date.
  293. *
  294. * \param[out] pdate Packed date for directory entry.
  295. *
  296. * \return true for success or false for failure.
  297. */
  298. bool getAccessDate(uint16_t* pdate);
  299. /** Get a file's access date and time.
  300. *
  301. * \param[out] pdate Packed date for directory entry.
  302. * \param[out] ptime return zero since FAT has no time.
  303. *
  304. * This function is for comparability in FsFile.
  305. *
  306. * \return true for success or false for failure.
  307. */
  308. bool getAccessDateTime(uint16_t* pdate, uint16_t* ptime) {
  309. if (!getAccessDate(pdate)) {
  310. return false;
  311. }
  312. *ptime = 0;
  313. return true;
  314. }
  315. /** Get a file's create date and time.
  316. *
  317. * \param[out] pdate Packed date for directory entry.
  318. * \param[out] ptime Packed time for directory entry.
  319. *
  320. * \return true for success or false for failure.
  321. */
  322. bool getCreateDateTime(uint16_t* pdate, uint16_t* ptime);
  323. /** \return All error bits. */
  324. uint8_t getError() const {return m_error;}
  325. /** Get a file's modify date and time.
  326. *
  327. * \param[out] pdate Packed date for directory entry.
  328. * \param[out] ptime Packed time for directory entry.
  329. *
  330. * \return true for success or false for failure.
  331. */
  332. bool getModifyDateTime(uint16_t* pdate, uint16_t* ptime);
  333. /**
  334. * Get a file's name followed by a zero byte.
  335. *
  336. * \param[out] name An array of characters for the file's name.
  337. * \param[in] size The size of the array in bytes. The array
  338. * must be at least 13 bytes long. The file's name will be
  339. * truncated if the file's name is too long.
  340. * \return length for success or zero for failure.
  341. */
  342. size_t getName(char* name, size_t size);
  343. /**
  344. * Get a file's ASCII name followed by a zero.
  345. *
  346. * \param[out] name An array of characters for the file's name.
  347. * \param[in] size The size of the array in characters.
  348. * \return the name length.
  349. */
  350. size_t getName7(char* name, size_t size);
  351. /**
  352. * Get a file's UTF-8 name followed by a zero.
  353. *
  354. * \param[out] name An array of characters for the file's name.
  355. * \param[in] size The size of the array in characters.
  356. * \return the name length.
  357. */
  358. size_t getName8(char* name, size_t size);
  359. #ifndef DOXYGEN_SHOULD_SKIP_THIS
  360. size_t __attribute__((error("use getSFN(name, size)"))) getSFN(char* name);
  361. #endif // DOXYGEN_SHOULD_SKIP_THIS
  362. /**
  363. * Get a file's Short File Name followed by a zero byte.
  364. *
  365. * \param[out] name An array of characters for the file's name.
  366. * The array should be at least 13 bytes long.
  367. * \param[in] size size of name array.
  368. * \return true for success or false for failure.
  369. */
  370. size_t getSFN(char* name, size_t size);
  371. /** \return value of writeError */
  372. bool getWriteError() const {
  373. return isOpen() ? m_error & WRITE_ERROR : true;
  374. }
  375. /**
  376. * Check for BlockDevice busy.
  377. *
  378. * \return true if busy else false.
  379. */
  380. bool isBusy();
  381. #if USE_FAT_FILE_FLAG_CONTIGUOUS
  382. /** \return True if the file is contiguous. */
  383. bool isContiguous() const {return m_flags & FILE_FLAG_CONTIGUOUS;}
  384. #endif // USE_FAT_FILE_FLAG_CONTIGUOUS
  385. /** \return True if this is a directory. */
  386. bool isDir() const {return m_attributes & FILE_ATTR_DIR;}
  387. /** \return True if this is a normal file. */
  388. bool isFile() const {return m_attributes & FILE_ATTR_FILE;}
  389. /** \return True if this is a hidden file. */
  390. bool isHidden() const {return m_attributes & FILE_ATTR_HIDDEN;}
  391. /** \return true if this file has a Long File Name. */
  392. bool isLFN() const {return m_lfnOrd;}
  393. /** \return True if this is an open file/directory. */
  394. bool isOpen() const {return m_attributes;}
  395. /** \return True file is readable. */
  396. bool isReadable() const {return m_flags & FILE_FLAG_READ;}
  397. /** \return True if file is read-only */
  398. bool isReadOnly() const {return m_attributes & FILE_ATTR_READ_ONLY;}
  399. /** \return True if this is the root directory. */
  400. bool isRoot() const {return m_attributes & FILE_ATTR_ROOT;}
  401. /** \return True if this is the FAT32 root directory. */
  402. bool isRoot32() const {return m_attributes & FILE_ATTR_ROOT32;}
  403. /** \return True if this is the FAT12 of FAT16 root directory. */
  404. bool isRootFixed() const {return m_attributes & FILE_ATTR_ROOT_FIXED;}
  405. /** \return True if this is a subdirectory. */
  406. bool isSubDir() const {return m_attributes & FILE_ATTR_SUBDIR;}
  407. /** \return True if this is a system file. */
  408. bool isSystem() const {return m_attributes & FILE_ATTR_SYSTEM;}
  409. /** \return True file is writable. */
  410. bool isWritable() const {return m_flags & FILE_FLAG_WRITE;}
  411. /** List directory contents.
  412. *
  413. * \param[in] pr Print stream for list.
  414. *
  415. * \param[in] flags The inclusive OR of
  416. *
  417. * LS_DATE - %Print file modification date
  418. *
  419. * LS_SIZE - %Print file size.
  420. *
  421. * LS_R - Recursive list of subdirectories.
  422. *
  423. * \param[in] indent Amount of space before file name. Used for recursive
  424. * list to indicate subdirectory level.
  425. *
  426. * \return true for success or false for failure.
  427. */
  428. bool ls(print_t* pr, uint8_t flags = 0, uint8_t indent = 0);
  429. /** Make a new directory.
  430. *
  431. * \param[in] dir An open FatFile instance for the directory that will
  432. * contain the new directory.
  433. *
  434. * \param[in] path A path with a valid name for the new directory.
  435. *
  436. * \param[in] pFlag Create missing parent directories if true.
  437. *
  438. * \return true for success or false for failure.
  439. */
  440. bool mkdir(FatFile* dir, const char* path, bool pFlag = true);
  441. /** No longer implemented due to Long File Names.
  442. *
  443. * Use getName(char* name, size_t size).
  444. * \return a pointer to replacement suggestion.
  445. */
  446. #ifndef DOXYGEN_SHOULD_SKIP_THIS
  447. const char* __attribute__((error("use getName(name, size)"))) name();
  448. #endif // DOXYGEN_SHOULD_SKIP_THIS
  449. /** Open a file in the volume root directory.
  450. *
  451. * \param[in] vol Volume where the file is located.
  452. *
  453. * \param[in] path with a valid name for a file to be opened.
  454. *
  455. * \param[in] oflag bitwise-inclusive OR of open flags.
  456. * See see FatFile::open(FatFile*, const char*, uint8_t).
  457. *
  458. * \return true for success or false for failure.
  459. */
  460. bool open(FatVolume* vol, const char* path, oflag_t oflag);
  461. /** Open a file by index.
  462. *
  463. * \param[in] dirFile An open FatFile instance for the directory.
  464. *
  465. * \param[in] index The \a index of the directory entry for the file to be
  466. * opened. The value for \a index is (directory file position)/32.
  467. *
  468. * \param[in] oflag bitwise-inclusive OR of open flags.
  469. * See see FatFile::open(FatFile*, const char*, uint8_t).
  470. *
  471. * See open() by path for definition of flags.
  472. * \return true for success or false for failure.
  473. */
  474. bool open(FatFile* dirFile, uint16_t index, oflag_t oflag);
  475. /** Open a file or directory by name.
  476. *
  477. * \param[in] dirFile An open FatFile instance for the directory containing
  478. * the file to be opened.
  479. *
  480. * \param[in] path A path with a valid name for a file to be opened.
  481. *
  482. * \param[in] oflag Values for \a oflag are constructed by a
  483. * bitwise-inclusive OR of flags from the following list.
  484. * Only one of O_RDONLY, O_READ, O_WRONLY, O_WRITE, or
  485. * O_RDWR is allowed.
  486. *
  487. * O_RDONLY - Open for reading.
  488. *
  489. * O_READ - Same as O_RDONLY.
  490. *
  491. * O_WRONLY - Open for writing.
  492. *
  493. * O_WRITE - Same as O_WRONLY.
  494. *
  495. * O_RDWR - Open for reading and writing.
  496. *
  497. * O_APPEND - If set, the file offset shall be set to the end of the
  498. * file prior to each write.
  499. *
  500. * O_AT_END - Set the initial position at the end of the file.
  501. *
  502. * O_CREAT - If the file exists, this flag has no effect except as noted
  503. * under O_EXCL below. Otherwise, the file shall be created
  504. *
  505. * O_EXCL - If O_CREAT and O_EXCL are set, open() shall fail if the file
  506. * exists.
  507. *
  508. * O_TRUNC - If the file exists and is a regular file, and the file is
  509. * successfully opened and is not read only, its length shall be truncated
  510. * to 0.
  511. *
  512. * WARNING: A given file must not be opened by more than one FatFile object
  513. * or file corruption may occur.
  514. *
  515. * \note Directory files must be opened read only. Write and truncation is
  516. * not allowed for directory files.
  517. *
  518. * \return true for success or false for failure.
  519. */
  520. bool open(FatFile* dirFile, const char* path, oflag_t oflag);
  521. /** Open a file in the current working volume.
  522. *
  523. * \param[in] path A path with a valid name for a file to be opened.
  524. *
  525. * \param[in] oflag bitwise-inclusive OR of open flags.
  526. * See see FatFile::open(FatFile*, const char*, uint8_t).
  527. *
  528. * \return true for success or false for failure.
  529. */
  530. bool open(const char* path, oflag_t oflag = O_RDONLY);
  531. /** Open existing file wih Short 8.3 names.
  532. * \param[in] path with short 8.3 names.
  533. *
  534. * the purpose of this function is to save flash on Uno
  535. * and other small boards.
  536. *
  537. * Directories will be opened O_RDONLY, files O_RDWR.
  538. * \return true for success or false for failure.
  539. */
  540. bool openExistingSFN(const char* path);
  541. /** Open the next file or subdirectory in a directory.
  542. *
  543. * \param[in] dirFile An open FatFile instance for the directory
  544. * containing the file to be opened.
  545. *
  546. * \param[in] oflag bitwise-inclusive OR of open flags.
  547. * See see FatFile::open(FatFile*, const char*, uint8_t).
  548. *
  549. * \return true for success or false for failure.
  550. */
  551. bool openNext(FatFile* dirFile, oflag_t oflag = O_RDONLY);
  552. /** Open a volume's root directory.
  553. *
  554. * \param[in] vol The FAT volume containing the root directory to be opened.
  555. *
  556. * \return true for success or false for failure.
  557. */
  558. bool openRoot(FatVolume* vol);
  559. /** Return the next available byte without consuming it.
  560. *
  561. * \return The byte if no error and not at eof else -1;
  562. */
  563. int peek();
  564. /** Allocate contiguous clusters to an empty file.
  565. *
  566. * The file must be empty with no clusters allocated.
  567. *
  568. * The file will contain uninitialized data.
  569. *
  570. * \param[in] length size of the file in bytes.
  571. * \return true for success or false for failure.
  572. */
  573. bool preAllocate(uint32_t length);
  574. /** Print a file's access date
  575. *
  576. * \param[in] pr Print stream for output.
  577. *
  578. * \return The number of characters printed.
  579. */
  580. size_t printAccessDate(print_t* pr);
  581. /** Print a file's access date
  582. *
  583. * \param[in] pr Print stream for output.
  584. *
  585. * \return The number of characters printed.
  586. */
  587. size_t printAccessDateTime(print_t* pr) {
  588. return printAccessDate(pr);
  589. }
  590. /** Print a file's creation date and time
  591. *
  592. * \param[in] pr Print stream for output.
  593. *
  594. * \return The number of bytes printed.
  595. */
  596. size_t printCreateDateTime(print_t* pr);
  597. /** %Print a directory date field.
  598. *
  599. * Format is yyyy-mm-dd.
  600. *
  601. * \param[in] pr Print stream for output.
  602. * \param[in] fatDate The date field from a directory entry.
  603. */
  604. static void printFatDate(print_t* pr, uint16_t fatDate);
  605. /** %Print a directory time field.
  606. *
  607. * Format is hh:mm:ss.
  608. *
  609. * \param[in] pr Print stream for output.
  610. * \param[in] fatTime The time field from a directory entry.
  611. */
  612. static void printFatTime(print_t* pr, uint16_t fatTime);
  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. * \param[in] prec Number of digits after decimal point.
  617. * \return The number of bytes written or -1 if an error occurs.
  618. */
  619. size_t printField(double value, char term, uint8_t prec = 2) {
  620. char buf[24];
  621. char* str = buf + sizeof(buf);
  622. if (term) {
  623. *--str = term;
  624. if (term == '\n') {
  625. *--str = '\r';
  626. }
  627. }
  628. str = fmtDouble(str, value, prec, false);
  629. return write(str, buf + sizeof(buf) - str);
  630. }
  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. * \param[in] prec Number of digits after decimal point.
  635. * \return The number of bytes written or -1 if an error occurs.
  636. */
  637. size_t printField(float value, char term, uint8_t prec = 2) {
  638. return printField(static_cast<double>(value), term, prec);
  639. }
  640. /** Print a number followed by a field terminator.
  641. * \param[in] value The number to be printed.
  642. * \param[in] term The field terminator. Use '\\n' for CR LF.
  643. * \return The number of bytes written or -1 if an error occurs.
  644. */
  645. template <typename Type>
  646. size_t printField(Type value, char term) {
  647. char sign = 0;
  648. char buf[3*sizeof(Type) + 3];
  649. char* str = buf + sizeof(buf);
  650. if (term) {
  651. *--str = term;
  652. if (term == '\n') {
  653. *--str = '\r';
  654. }
  655. }
  656. if (value < 0) {
  657. value = -value;
  658. sign = '-';
  659. }
  660. if (sizeof(Type) < 4) {
  661. str = fmtBase10(str, (uint16_t)value);
  662. } else {
  663. str = fmtBase10(str, (uint32_t)value);
  664. }
  665. if (sign) {
  666. *--str = sign;
  667. }
  668. return write(str, &buf[sizeof(buf)] - str);
  669. }
  670. /** Print a file's size.
  671. *
  672. * \param[in] pr Print stream for output.
  673. *
  674. * \return The number of characters printed is returned
  675. * for success and zero is returned for failure.
  676. */
  677. size_t printFileSize(print_t* pr);
  678. /** Print a file's modify date and time
  679. *
  680. * \param[in] pr Print stream for output.
  681. *
  682. * \return The number of characters printed.
  683. */
  684. size_t printModifyDateTime(print_t* pr);
  685. /** Print a file's name
  686. *
  687. * \param[in] pr Print stream for output.
  688. *
  689. * \return length for success or zero for failure.
  690. */
  691. size_t printName(print_t* pr);
  692. /** Print a file's ASCII name
  693. *
  694. * \param[in] pr Print stream for output.
  695. *
  696. * \return true for success or false for failure.
  697. */
  698. size_t printName7(print_t* pr);
  699. /** Print a file's UTF-8 name
  700. *
  701. * \param[in] pr Print stream for output.
  702. *
  703. * \return true for success or false for failure.
  704. */
  705. size_t printName8(print_t* pr);
  706. /** Print a file's Short File Name.
  707. *
  708. * \param[in] pr Print stream for output.
  709. *
  710. * \return The number of characters printed is returned
  711. * for success and zero is returned for failure.
  712. */
  713. size_t printSFN(print_t* pr);
  714. /** Read the next byte from a file.
  715. *
  716. * \return For success read returns the next byte in the file as an int.
  717. * If an error occurs or end of file is reached -1 is returned.
  718. */
  719. int read() {
  720. uint8_t b;
  721. return read(&b, 1) == 1 ? b : -1;
  722. }
  723. /** Read data from a file starting at the current position.
  724. *
  725. * \param[out] buf Pointer to the location that will receive the data.
  726. *
  727. * \param[in] count Maximum number of bytes to read.
  728. *
  729. * \return For success read() returns the number of bytes read.
  730. * A value less than \a nbyte, including zero, will be returned
  731. * if end of file is reached.
  732. * If an error occurs, read() returns -1.
  733. */
  734. int read(void* buf, size_t count);
  735. /** Read the next directory entry from a directory file.
  736. *
  737. * \param[out] dir The DirFat_t struct that will receive the data.
  738. *
  739. * \return For success readDir() returns the number of bytes read.
  740. * A value of zero will be returned if end of file is reached.
  741. * If an error occurs, readDir() returns -1. Possible errors include
  742. * readDir() called before a directory has been opened, this is not
  743. * a directory file or an I/O error occurred.
  744. */
  745. int8_t readDir(DirFat_t* dir);
  746. /** Remove a file.
  747. *
  748. * The directory entry and all data for the file are deleted.
  749. *
  750. * \note This function should not be used to delete the 8.3 version of a
  751. * file that has a long name. For example if a file has the long name
  752. * "New Text Document.txt" you should not delete the 8.3 name "NEWTEX~1.TXT".
  753. *
  754. * \return true for success or false for failure.
  755. */
  756. bool remove();
  757. /** Remove a file.
  758. *
  759. * The directory entry and all data for the file are deleted.
  760. *
  761. * \param[in] path Path for the file to be removed.
  762. *
  763. * Example use: dirFile.remove(filenameToRemove);
  764. *
  765. * \note This function should not be used to delete the 8.3 version of a
  766. * file that has a long name. For example if a file has the long name
  767. * "New Text Document.txt" you should not delete the 8.3 name "NEWTEX~1.TXT".
  768. *
  769. * \return true for success or false for failure.
  770. */
  771. bool remove(const char* path);
  772. /** Rename a file or subdirectory.
  773. * \note the renamed file will be moved to the current volume working
  774. * directory.
  775. *
  776. * \param[in] newPath New path name for the file/directory.
  777. *
  778. * \return true for success or false for failure.
  779. */
  780. bool rename(const char* newPath);
  781. /** Rename a file or subdirectory.
  782. *
  783. * \param[in] dirFile Directory for the new path.
  784. * \param[in] newPath New path name for the file/directory.
  785. *
  786. * \return true for success or false for failure.
  787. */
  788. bool rename(FatFile* dirFile, const char* newPath);
  789. /** Set the file's current position to zero. */
  790. void rewind() {
  791. seekSet(0);
  792. }
  793. /** Remove a directory file.
  794. *
  795. * The directory file will be removed only if it is empty and is not the
  796. * root directory. rmdir() follows DOS and Windows and ignores the
  797. * read-only attribute for the directory.
  798. *
  799. * \note This function should not be used to delete the 8.3 version of a
  800. * directory that has a long name. For example if a directory has the
  801. * long name "New folder" you should not delete the 8.3 name "NEWFOL~1".
  802. *
  803. * \return true for success or false for failure.
  804. */
  805. bool rmdir();
  806. /** Recursively delete a directory and all contained files.
  807. *
  808. * This is like the Unix/Linux 'rm -rf *' if called with the root directory
  809. * hence the name.
  810. *
  811. * Warning - This will remove all contents of the directory including
  812. * subdirectories. The directory will then be removed if it is not root.
  813. * The read-only attribute for files will be ignored.
  814. *
  815. * \note This function should not be used to delete the 8.3 version of
  816. * a directory that has a long name. See remove() and rmdir().
  817. *
  818. * \return true for success or false for failure.
  819. */
  820. bool rmRfStar();
  821. /** Set the files position to current position + \a pos. See seekSet().
  822. * \param[in] offset The new position in bytes from the current position.
  823. * \return true for success or false for failure.
  824. */
  825. bool seekCur(int32_t offset) {
  826. return seekSet(m_curPosition + offset);
  827. }
  828. /** Set the files position to end-of-file + \a offset. See seekSet().
  829. * Can't be used for directory files since file size is not defined.
  830. * \param[in] offset The new position in bytes from end-of-file.
  831. * \return true for success or false for failure.
  832. */
  833. bool seekEnd(int32_t offset = 0) {
  834. return isFile() ? seekSet(m_fileSize + offset) : false;
  835. }
  836. /** Sets a file's position.
  837. *
  838. * \param[in] pos The new position in bytes from the beginning of the file.
  839. *
  840. * \return true for success or false for failure.
  841. */
  842. bool seekSet(uint32_t pos);
  843. /** The sync() call causes all modified data and directory fields
  844. * to be written to the storage device.
  845. *
  846. * \return true for success or false for failure.
  847. */
  848. bool sync();
  849. /** Set a file's timestamps in its directory entry.
  850. *
  851. * \param[in] flags Values for \a flags are constructed by a bitwise-inclusive
  852. * OR of flags from the following list
  853. *
  854. * T_ACCESS - Set the file's last access date.
  855. *
  856. * T_CREATE - Set the file's creation date and time.
  857. *
  858. * T_WRITE - Set the file's last write/modification date and time.
  859. *
  860. * \param[in] year Valid range 1980 - 2107 inclusive.
  861. *
  862. * \param[in] month Valid range 1 - 12 inclusive.
  863. *
  864. * \param[in] day Valid range 1 - 31 inclusive.
  865. *
  866. * \param[in] hour Valid range 0 - 23 inclusive.
  867. *
  868. * \param[in] minute Valid range 0 - 59 inclusive.
  869. *
  870. * \param[in] second Valid range 0 - 59 inclusive
  871. *
  872. * \note It is possible to set an invalid date since there is no check for
  873. * the number of days in a month.
  874. *
  875. * \note
  876. * Modify and access timestamps may be overwritten if a date time callback
  877. * function has been set by dateTimeCallback().
  878. *
  879. * \return true for success or false for failure.
  880. */
  881. bool timestamp(uint8_t flags, uint16_t year, uint8_t month, uint8_t day,
  882. uint8_t hour, uint8_t minute, uint8_t second);
  883. /** Truncate a file at the current file position.
  884. * will be maintained if it is less than or equal to \a length otherwise
  885. * it will be set to end of file.
  886. *
  887. * \return true for success or false for failure.
  888. */
  889. bool truncate();
  890. /** Truncate a file to a specified length. The current file position
  891. * will be set to end of file.
  892. *
  893. * \param[in] length The desired length for the file.
  894. *
  895. * \return true for success or false for failure.
  896. */
  897. bool truncate(uint32_t length) {
  898. return seekSet(length) && truncate();
  899. }
  900. /** Write a string to a file. Used by the Arduino Print class.
  901. * \param[in] str Pointer to the string.
  902. * Use getWriteError to check for errors.
  903. * \return count of characters written for success or -1 for failure.
  904. */
  905. size_t write(const char* str) {
  906. return write(str, strlen(str));
  907. }
  908. /** Write a single byte.
  909. * \param[in] b The byte to be written.
  910. * \return +1 for success or -1 for failure.
  911. */
  912. size_t write(uint8_t b) {
  913. return write(&b, 1);
  914. }
  915. /** Write data to an open file.
  916. *
  917. * \note Data is moved to the cache but may not be written to the
  918. * storage device until sync() is called.
  919. *
  920. * \param[in] buf Pointer to the location of the data to be written.
  921. *
  922. * \param[in] count Number of bytes to write.
  923. *
  924. * \return For success write() returns the number of bytes written, always
  925. * \a count. If an error occurs, write() returns zero and writeError is set.
  926. *
  927. */
  928. size_t write(const void* buf, size_t count);
  929. //------------------------------------------------------------------------------
  930. #if ENABLE_ARDUINO_SERIAL
  931. /** List directory contents.
  932. *
  933. * \param[in] flags The inclusive OR of
  934. *
  935. * LS_DATE - %Print file modification date
  936. *
  937. * LS_SIZE - %Print file size.
  938. *
  939. * LS_R - Recursive list of subdirectories.
  940. *
  941. * \return true for success or false for failure.
  942. */
  943. bool ls(uint8_t flags = 0) {
  944. return ls(&Serial, flags);
  945. }
  946. /** Print a file's name.
  947. *
  948. * \return length for success or zero for failure.
  949. */
  950. size_t printName() {
  951. return FatFile::printName(&Serial);
  952. }
  953. #endif // ENABLE_ARDUINO_SERIAL
  954. private:
  955. /** FatVolume allowed access to private members. */
  956. friend class FatVolume;
  957. /** This file has not been opened. */
  958. static const uint8_t FILE_ATTR_CLOSED = 0;
  959. /** File is read-only. */
  960. static const uint8_t FILE_ATTR_READ_ONLY = FAT_ATTRIB_READ_ONLY;
  961. /** File should be hidden in directory listings. */
  962. static const uint8_t FILE_ATTR_HIDDEN = FAT_ATTRIB_HIDDEN;
  963. /** Entry is for a system file. */
  964. static const uint8_t FILE_ATTR_SYSTEM = FAT_ATTRIB_SYSTEM;
  965. /** Entry for normal data file */
  966. static const uint8_t FILE_ATTR_FILE = 0X08;
  967. /** Entry is for a subdirectory */
  968. static const uint8_t FILE_ATTR_SUBDIR = FAT_ATTRIB_DIRECTORY;
  969. /** A FAT12 or FAT16 root directory */
  970. static const uint8_t FILE_ATTR_ROOT_FIXED = 0X20;
  971. /** A FAT32 root directory */
  972. static const uint8_t FILE_ATTR_ROOT32 = 0X40;
  973. /** Entry is for root. */
  974. static const uint8_t FILE_ATTR_ROOT =
  975. FILE_ATTR_ROOT_FIXED | FILE_ATTR_ROOT32;
  976. /** Directory type bits */
  977. static const uint8_t FILE_ATTR_DIR = FILE_ATTR_SUBDIR | FILE_ATTR_ROOT;
  978. /** Attributes to copy from directory entry */
  979. static const uint8_t FILE_ATTR_COPY =
  980. FAT_ATTRIB_READ_ONLY | FAT_ATTRIB_HIDDEN |
  981. FAT_ATTRIB_SYSTEM | FAT_ATTRIB_DIRECTORY;
  982. // private functions
  983. bool addCluster();
  984. bool addDirCluster();
  985. DirFat_t* cacheDir(uint16_t index) {
  986. return seekSet(32UL*index) ? readDirCache() : nullptr;
  987. }
  988. DirFat_t* cacheDirEntry(uint8_t action);
  989. bool cmpName(uint16_t index, FatLfn_t* fname, uint8_t lfnOrd);
  990. bool createLFN(uint16_t index, FatLfn_t* fname, uint8_t lfnOrd);
  991. uint16_t getLfnChar(DirLfn_t* ldir, uint8_t i);
  992. uint8_t lfnChecksum(uint8_t* name) {
  993. uint8_t sum = 0;
  994. for (uint8_t i = 0; i < 11; i++) {
  995. sum = (((sum & 1) << 7) | (sum >> 1)) + name[i];
  996. }
  997. return sum;
  998. }
  999. static bool makeSFN(FatLfn_t* fname);
  1000. bool makeUniqueSfn(FatLfn_t* fname);
  1001. bool openCluster(FatFile* file);
  1002. bool parsePathName(const char* str, FatLfn_t* fname, const char** ptr);
  1003. bool parsePathName(const char* str, FatSfn_t* fname, const char** ptr);
  1004. bool mkdir(FatFile* parent, FatName_t* fname);
  1005. bool open(FatFile* dirFile, FatLfn_t* fname, oflag_t oflag);
  1006. bool open(FatFile* dirFile, FatSfn_t* fname, oflag_t oflag);
  1007. bool openSFN(FatSfn_t* fname);
  1008. bool openCachedEntry(FatFile* dirFile, uint16_t cacheIndex, oflag_t oflag,
  1009. uint8_t lfnOrd);
  1010. DirFat_t* readDirCache(bool skipReadOk = false);
  1011. // bits defined in m_flags
  1012. static const uint8_t FILE_FLAG_READ = 0X01;
  1013. static const uint8_t FILE_FLAG_WRITE = 0X02;
  1014. static const uint8_t FILE_FLAG_APPEND = 0X08;
  1015. // treat curPosition as valid length.
  1016. static const uint8_t FILE_FLAG_PREALLOCATE = 0X20;
  1017. // file is contiguous
  1018. static const uint8_t FILE_FLAG_CONTIGUOUS = 0X40;
  1019. // sync of directory entry required
  1020. static const uint8_t FILE_FLAG_DIR_DIRTY = 0X80;
  1021. // private data
  1022. static const uint8_t WRITE_ERROR = 0X1;
  1023. static const uint8_t READ_ERROR = 0X2;
  1024. uint8_t m_attributes = FILE_ATTR_CLOSED;
  1025. uint8_t m_error = 0; // Error bits.
  1026. uint8_t m_flags = 0; // See above for definition of m_flags bits
  1027. uint8_t m_lfnOrd;
  1028. uint16_t m_dirIndex; // index of directory entry in dir file
  1029. FatVolume* m_vol; // volume where file is located
  1030. uint32_t m_dirCluster;
  1031. uint32_t m_curCluster; // cluster for current file position
  1032. uint32_t m_curPosition; // current file position
  1033. uint32_t m_dirSector; // sector for this files directory entry
  1034. uint32_t m_fileSize; // file size in bytes
  1035. uint32_t m_firstCluster; // first cluster of file
  1036. };
  1037. #include "../common/ArduinoFiles.h"
  1038. /**
  1039. * \class File32
  1040. * \brief FAT16/FAT32 file with Arduino Stream.
  1041. */
  1042. class File32 : public StreamFile<FatFile, uint32_t> {
  1043. public:
  1044. /** Opens the next file or folder in a directory.
  1045. *
  1046. * \param[in] oflag open flags.
  1047. * \return a FatStream object.
  1048. */
  1049. File32 openNextFile(oflag_t oflag = O_RDONLY) {
  1050. File32 tmpFile;
  1051. tmpFile.openNext(this, oflag);
  1052. return tmpFile;
  1053. }
  1054. };
  1055. #endif // FatFile_h