My Marlin configs for Fabrikator Mini and CTC i3 Pro B
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.

SdBaseFile.cpp 50KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766
  1. /**
  2. * Marlin 3D Printer Firmware
  3. * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin]
  4. *
  5. * Based on Sprinter and grbl.
  6. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm
  7. *
  8. * This program is free software: you can redistribute it and/or modify
  9. * it under the terms of the GNU General Public License as published by
  10. * the Free Software Foundation, either version 3 of the License, or
  11. * (at your option) any later version.
  12. *
  13. * This program is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU General Public License
  19. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  20. *
  21. */
  22. #if __GNUC__ > 8
  23. #pragma GCC diagnostic ignored "-Waddress-of-packed-member"
  24. #endif
  25. /**
  26. * sd/SdBaseFile.cpp
  27. *
  28. * Arduino SdFat Library
  29. * Copyright (c) 2009 by William Greiman
  30. *
  31. * This file is part of the Arduino Sd2Card Library
  32. */
  33. #include "../inc/MarlinConfig.h"
  34. #if ENABLED(SDSUPPORT)
  35. #include "SdBaseFile.h"
  36. #include "../MarlinCore.h"
  37. SdBaseFile* SdBaseFile::cwd_ = 0; // Pointer to Current Working Directory
  38. // callback function for date/time
  39. void (*SdBaseFile::dateTime_)(uint16_t* date, uint16_t* time) = 0;
  40. // add a cluster to a file
  41. bool SdBaseFile::addCluster() {
  42. if (ENABLED(SDCARD_READONLY)) return false;
  43. if (!vol_->allocContiguous(1, &curCluster_)) return false;
  44. // if first cluster of file link to directory entry
  45. if (firstCluster_ == 0) {
  46. firstCluster_ = curCluster_;
  47. flags_ |= F_FILE_DIR_DIRTY;
  48. }
  49. return true;
  50. }
  51. // Add a cluster to a directory file and zero the cluster.
  52. // return with first block of cluster in the cache
  53. bool SdBaseFile::addDirCluster() {
  54. if (ENABLED(SDCARD_READONLY)) return false;
  55. uint32_t block;
  56. // max folder size
  57. if (fileSize_ / sizeof(dir_t) >= 0xFFFF) return false;
  58. if (!addCluster()) return false;
  59. if (!vol_->cacheFlush()) return false;
  60. block = vol_->clusterStartBlock(curCluster_);
  61. // set cache to first block of cluster
  62. vol_->cacheSetBlockNumber(block, true);
  63. // zero first block of cluster
  64. memset(vol_->cacheBuffer_.data, 0, 512);
  65. // zero rest of cluster
  66. for (uint8_t i = 1; i < vol_->blocksPerCluster_; i++) {
  67. if (!vol_->writeBlock(block + i, vol_->cacheBuffer_.data)) return false;
  68. }
  69. // Increase directory file size by cluster size
  70. fileSize_ += 512UL << vol_->clusterSizeShift_;
  71. return true;
  72. }
  73. // cache a file's directory entry
  74. // return pointer to cached entry or null for failure
  75. dir_t* SdBaseFile::cacheDirEntry(uint8_t action) {
  76. if (!vol_->cacheRawBlock(dirBlock_, action)) return nullptr;
  77. return vol_->cache()->dir + dirIndex_;
  78. }
  79. /**
  80. * Close a file and force cached data and directory information
  81. * to be written to the storage device.
  82. *
  83. * \return true for success, false for failure.
  84. * Reasons for failure include no file is open or an I/O error.
  85. */
  86. bool SdBaseFile::close() {
  87. bool rtn = sync();
  88. type_ = FAT_FILE_TYPE_CLOSED;
  89. return rtn;
  90. }
  91. /**
  92. * Check for contiguous file and return its raw block range.
  93. *
  94. * \param[out] bgnBlock the first block address for the file.
  95. * \param[out] endBlock the last block address for the file.
  96. *
  97. * \return true for success, false for failure.
  98. * Reasons for failure include file is not contiguous, file has zero length
  99. * or an I/O error occurred.
  100. */
  101. bool SdBaseFile::contiguousRange(uint32_t* bgnBlock, uint32_t* endBlock) {
  102. // error if no blocks
  103. if (firstCluster_ == 0) return false;
  104. for (uint32_t c = firstCluster_; ; c++) {
  105. uint32_t next;
  106. if (!vol_->fatGet(c, &next)) return false;
  107. // check for contiguous
  108. if (next != (c + 1)) {
  109. // error if not end of chain
  110. if (!vol_->isEOC(next)) return false;
  111. *bgnBlock = vol_->clusterStartBlock(firstCluster_);
  112. *endBlock = vol_->clusterStartBlock(c)
  113. + vol_->blocksPerCluster_ - 1;
  114. return true;
  115. }
  116. }
  117. return false;
  118. }
  119. /**
  120. * Create and open a new contiguous file of a specified size.
  121. *
  122. * \note This function only supports short DOS 8.3 names.
  123. * See open() for more information.
  124. *
  125. * \param[in] dirFile The directory where the file will be created.
  126. * \param[in] path A path with a valid DOS 8.3 file name.
  127. * \param[in] size The desired file size.
  128. *
  129. * \return true for success, false for failure.
  130. * Reasons for failure include \a path contains
  131. * an invalid DOS 8.3 file name, the FAT volume has not been initialized,
  132. * a file is already open, the file already exists, the root
  133. * directory is full or an I/O error.
  134. */
  135. bool SdBaseFile::createContiguous(SdBaseFile* dirFile, const char* path, uint32_t size) {
  136. if (ENABLED(SDCARD_READONLY)) return false;
  137. uint32_t count;
  138. // don't allow zero length file
  139. if (size == 0) return false;
  140. if (!open(dirFile, path, O_CREAT | O_EXCL | O_RDWR)) return false;
  141. // calculate number of clusters needed
  142. count = ((size - 1) >> (vol_->clusterSizeShift_ + 9)) + 1;
  143. // allocate clusters
  144. if (!vol_->allocContiguous(count, &firstCluster_)) {
  145. remove();
  146. return false;
  147. }
  148. fileSize_ = size;
  149. // insure sync() will update dir entry
  150. flags_ |= F_FILE_DIR_DIRTY;
  151. return sync();
  152. }
  153. /**
  154. * Return a file's directory entry.
  155. *
  156. * \param[out] dir Location for return of the file's directory entry.
  157. *
  158. * \return true for success, false for failure.
  159. */
  160. bool SdBaseFile::dirEntry(dir_t* dir) {
  161. dir_t* p;
  162. // make sure fields on SD are correct
  163. if (!sync()) return false;
  164. // read entry
  165. p = cacheDirEntry(SdVolume::CACHE_FOR_READ);
  166. if (!p) return false;
  167. // copy to caller's struct
  168. memcpy(dir, p, sizeof(dir_t));
  169. return true;
  170. }
  171. /**
  172. * Format the name field of \a dir into the 13 byte array
  173. * \a name in standard 8.3 short name format.
  174. *
  175. * \param[in] dir The directory structure containing the name.
  176. * \param[out] name A 13 byte char array for the formatted name.
  177. */
  178. void SdBaseFile::dirName(const dir_t& dir, char* name) {
  179. uint8_t j = 0;
  180. LOOP_L_N(i, 11) {
  181. if (dir.name[i] == ' ')continue;
  182. if (i == 8) name[j++] = '.';
  183. name[j++] = dir.name[i];
  184. }
  185. name[j] = 0;
  186. }
  187. /**
  188. * Test for the existence of a file in a directory
  189. *
  190. * \param[in] name Name of the file to be tested for.
  191. *
  192. * The calling instance must be an open directory file.
  193. *
  194. * dirFile.exists("TOFIND.TXT") searches for "TOFIND.TXT" in the directory
  195. * dirFile.
  196. *
  197. * \return true if the file exists else false.
  198. */
  199. bool SdBaseFile::exists(const char* name) {
  200. SdBaseFile file;
  201. return file.open(this, name, O_READ);
  202. }
  203. /**
  204. * Get a string from a file.
  205. *
  206. * fgets() reads bytes from a file into the array pointed to by \a str, until
  207. * \a num - 1 bytes are read, or a delimiter is read and transferred to \a str,
  208. * or end-of-file is encountered. The string is then terminated
  209. * with a null byte.
  210. *
  211. * fgets() deletes CR, '\\r', from the string. This insures only a '\\n'
  212. * terminates the string for Windows text files which use CRLF for newline.
  213. *
  214. * \param[out] str Pointer to the array where the string is stored.
  215. * \param[in] num Maximum number of characters to be read
  216. * (including the final null byte). Usually the length
  217. * of the array \a str is used.
  218. * \param[in] delim Optional set of delimiters. The default is "\n".
  219. *
  220. * \return For success fgets() returns the length of the string in \a str.
  221. * If no data is read, fgets() returns zero for EOF or -1 if an error occurred.
  222. **/
  223. int16_t SdBaseFile::fgets(char* str, int16_t num, char* delim) {
  224. char ch;
  225. int16_t n = 0;
  226. int16_t r = -1;
  227. while ((n + 1) < num && (r = read(&ch, 1)) == 1) {
  228. // delete CR
  229. if (ch == '\r') continue;
  230. str[n++] = ch;
  231. if (!delim) {
  232. if (ch == '\n') break;
  233. }
  234. else {
  235. if (strchr(delim, ch)) break;
  236. }
  237. }
  238. if (r < 0) {
  239. // read error
  240. return -1;
  241. }
  242. str[n] = '\0';
  243. return n;
  244. }
  245. /**
  246. * Get a file's name
  247. *
  248. * \param[out] name An array of 13 characters for the file's name.
  249. *
  250. * \return true for success, false for failure.
  251. */
  252. bool SdBaseFile::getDosName(char * const name) {
  253. if (!isOpen()) return false;
  254. if (isRoot()) {
  255. name[0] = '/';
  256. name[1] = '\0';
  257. return true;
  258. }
  259. // cache entry
  260. dir_t* p = cacheDirEntry(SdVolume::CACHE_FOR_READ);
  261. if (!p) return false;
  262. // format name
  263. dirName(*p, name);
  264. return true;
  265. }
  266. void SdBaseFile::getpos(filepos_t* pos) {
  267. pos->position = curPosition_;
  268. pos->cluster = curCluster_;
  269. }
  270. /**
  271. * List directory contents.
  272. *
  273. * \param[in] pr Print stream for list.
  274. *
  275. * \param[in] flags The inclusive OR of
  276. *
  277. * LS_DATE - %Print file modification date
  278. *
  279. * LS_SIZE - %Print file size.
  280. *
  281. * LS_R - Recursive list of subdirectories.
  282. *
  283. * \param[in] indent Amount of space before file name. Used for recursive
  284. * list to indicate subdirectory level.
  285. */
  286. void SdBaseFile::ls(uint8_t flags, uint8_t indent) {
  287. rewind();
  288. int8_t status;
  289. while ((status = lsPrintNext(flags, indent))) {
  290. if (status > 1 && (flags & LS_R)) {
  291. uint16_t index = curPosition() / 32 - 1;
  292. SdBaseFile s;
  293. if (s.open(this, index, O_READ)) s.ls(flags, indent + 2);
  294. seekSet(32 * (index + 1));
  295. }
  296. }
  297. }
  298. // saves 32 bytes on stack for ls recursion
  299. // return 0 - EOF, 1 - normal file, or 2 - directory
  300. int8_t SdBaseFile::lsPrintNext(uint8_t flags, uint8_t indent) {
  301. dir_t dir;
  302. uint8_t w = 0;
  303. while (1) {
  304. if (read(&dir, sizeof(dir)) != sizeof(dir)) return 0;
  305. if (dir.name[0] == DIR_NAME_FREE) return 0;
  306. // skip deleted entry and entries for . and ..
  307. if (dir.name[0] != DIR_NAME_DELETED && dir.name[0] != '.'
  308. && DIR_IS_FILE_OR_SUBDIR(&dir)) break;
  309. }
  310. // indent for dir level
  311. LOOP_L_N(i, indent) SERIAL_CHAR(' ');
  312. // print name
  313. LOOP_L_N(i, 11) {
  314. if (dir.name[i] == ' ')continue;
  315. if (i == 8) {
  316. SERIAL_CHAR('.');
  317. w++;
  318. }
  319. SERIAL_CHAR(dir.name[i]);
  320. w++;
  321. }
  322. if (DIR_IS_SUBDIR(&dir)) {
  323. SERIAL_CHAR('/');
  324. w++;
  325. }
  326. if (flags & (LS_DATE | LS_SIZE)) {
  327. while (w++ < 14) SERIAL_CHAR(' ');
  328. }
  329. // print modify date/time if requested
  330. if (flags & LS_DATE) {
  331. SERIAL_CHAR(' ');
  332. printFatDate(dir.lastWriteDate);
  333. SERIAL_CHAR(' ');
  334. printFatTime(dir.lastWriteTime);
  335. }
  336. // print size if requested
  337. if (!DIR_IS_SUBDIR(&dir) && (flags & LS_SIZE)) {
  338. SERIAL_CHAR(' ');
  339. SERIAL_ECHO(dir.fileSize);
  340. }
  341. SERIAL_EOL();
  342. return DIR_IS_FILE(&dir) ? 1 : 2;
  343. }
  344. // Format directory name field from a 8.3 name string
  345. bool SdBaseFile::make83Name(const char* str, uint8_t* name, const char** ptr) {
  346. uint8_t n = 7, // Max index until a dot is found
  347. i = 11;
  348. while (i) name[--i] = ' '; // Set whole FILENAME.EXT to spaces
  349. while (*str && *str != '/') { // For each character, until nul or '/'
  350. uint8_t c = *str++; // Get char and advance
  351. if (c == '.') { // For a dot...
  352. if (n == 10) return false; // Already moved the max index? fail!
  353. n = 10; // Move the max index for full 8.3 name
  354. i = 8; // Move up to the extension place
  355. }
  356. else {
  357. // Fail for illegal characters
  358. PGM_P p = PSTR("|<>^+=?/[];,*\"\\");
  359. while (uint8_t b = pgm_read_byte(p++)) if (b == c) return false;
  360. if (i > n || c < 0x21 || c == 0x7F) return false; // Check size, non-printable characters
  361. name[i++] = (c < 'a' || c > 'z') ? (c) : (c + ('A' - 'a')); // Uppercase required for 8.3 name
  362. }
  363. }
  364. *ptr = str; // Set passed pointer to the end
  365. return name[0] != ' '; // Return true if any name was set
  366. }
  367. /**
  368. * Make a new directory.
  369. *
  370. * \param[in] parent An open SdFat instance for the directory that will contain
  371. * the new directory.
  372. *
  373. * \param[in] path A path with a valid 8.3 DOS name for the new directory.
  374. *
  375. * \param[in] pFlag Create missing parent directories if true.
  376. *
  377. * \return true for success, false for failure.
  378. * Reasons for failure include this file is already open, \a parent is not a
  379. * directory, \a path is invalid or already exists in \a parent.
  380. */
  381. bool SdBaseFile::mkdir(SdBaseFile* parent, const char* path, bool pFlag) {
  382. if (ENABLED(SDCARD_READONLY)) return false;
  383. uint8_t dname[11];
  384. SdBaseFile dir1, dir2;
  385. SdBaseFile* sub = &dir1;
  386. SdBaseFile* start = parent;
  387. if (!parent || isOpen()) return false;
  388. if (*path == '/') {
  389. while (*path == '/') path++;
  390. if (!parent->isRoot()) {
  391. if (!dir2.openRoot(parent->vol_)) return false;
  392. parent = &dir2;
  393. }
  394. }
  395. while (1) {
  396. if (!make83Name(path, dname, &path)) return false;
  397. while (*path == '/') path++;
  398. if (!*path) break;
  399. if (!sub->open(parent, dname, O_READ)) {
  400. if (!pFlag || !sub->mkdir(parent, dname))
  401. return false;
  402. }
  403. if (parent != start) parent->close();
  404. parent = sub;
  405. sub = parent != &dir1 ? &dir1 : &dir2;
  406. }
  407. return mkdir(parent, dname);
  408. }
  409. bool SdBaseFile::mkdir(SdBaseFile* parent, const uint8_t dname[11]) {
  410. if (ENABLED(SDCARD_READONLY)) return false;
  411. uint32_t block;
  412. dir_t d;
  413. dir_t* p;
  414. if (!parent->isDir()) return false;
  415. // create a normal file
  416. if (!open(parent, dname, O_CREAT | O_EXCL | O_RDWR)) return false;
  417. // convert file to directory
  418. flags_ = O_READ;
  419. type_ = FAT_FILE_TYPE_SUBDIR;
  420. // allocate and zero first cluster
  421. if (!addDirCluster()) return false;
  422. // force entry to SD
  423. if (!sync()) return false;
  424. // cache entry - should already be in cache due to sync() call
  425. p = cacheDirEntry(SdVolume::CACHE_FOR_WRITE);
  426. if (!p) return false;
  427. // change directory entry attribute
  428. p->attributes = DIR_ATT_DIRECTORY;
  429. // make entry for '.'
  430. memcpy(&d, p, sizeof(d));
  431. d.name[0] = '.';
  432. LOOP_S_L_N(i, 1, 11) d.name[i] = ' ';
  433. // cache block for '.' and '..'
  434. block = vol_->clusterStartBlock(firstCluster_);
  435. if (!vol_->cacheRawBlock(block, SdVolume::CACHE_FOR_WRITE)) return false;
  436. // copy '.' to block
  437. memcpy(&vol_->cache()->dir[0], &d, sizeof(d));
  438. // make entry for '..'
  439. d.name[1] = '.';
  440. if (parent->isRoot()) {
  441. d.firstClusterLow = 0;
  442. d.firstClusterHigh = 0;
  443. }
  444. else {
  445. d.firstClusterLow = parent->firstCluster_ & 0xFFFF;
  446. d.firstClusterHigh = parent->firstCluster_ >> 16;
  447. }
  448. // copy '..' to block
  449. memcpy(&vol_->cache()->dir[1], &d, sizeof(d));
  450. // write first block
  451. return vol_->cacheFlush();
  452. }
  453. /**
  454. * Open a file in the current working directory.
  455. *
  456. * \param[in] path A path with a valid 8.3 DOS name for a file to be opened.
  457. *
  458. * \param[in] oflag Values for \a oflag are constructed by a bitwise-inclusive
  459. * OR of open flags. see SdBaseFile::open(SdBaseFile*, const char*, uint8_t).
  460. *
  461. * \return true for success, false for failure.
  462. */
  463. bool SdBaseFile::open(const char* path, uint8_t oflag) {
  464. return open(cwd_, path, oflag);
  465. }
  466. /**
  467. * Open a file or directory by name.
  468. *
  469. * \param[in] dirFile An open SdFat instance for the directory containing the
  470. * file to be opened.
  471. *
  472. * \param[in] path A path with a valid 8.3 DOS name for a file to be opened.
  473. *
  474. * \param[in] oflag Values for \a oflag are constructed by a bitwise-inclusive
  475. * OR of flags from the following list
  476. *
  477. * O_READ - Open for reading.
  478. *
  479. * O_RDONLY - Same as O_READ.
  480. *
  481. * O_WRITE - Open for writing.
  482. *
  483. * O_WRONLY - Same as O_WRITE.
  484. *
  485. * O_RDWR - Open for reading and writing.
  486. *
  487. * O_APPEND - If set, the file offset shall be set to the end of the
  488. * file prior to each write.
  489. *
  490. * O_AT_END - Set the initial position at the end of the file.
  491. *
  492. * O_CREAT - If the file exists, this flag has no effect except as noted
  493. * under O_EXCL below. Otherwise, the file shall be created
  494. *
  495. * O_EXCL - If O_CREAT and O_EXCL are set, open() shall fail if the file exists.
  496. *
  497. * O_SYNC - Call sync() after each write. This flag should not be used with
  498. * write(uint8_t), write_P(PGM_P), writeln_P(PGM_P), or the Arduino Print class.
  499. * These functions do character at a time writes so sync() will be called
  500. * after each byte.
  501. *
  502. * O_TRUNC - If the file exists and is a regular file, and the file is
  503. * successfully opened and is not read only, its length shall be truncated to 0.
  504. *
  505. * WARNING: A given file must not be opened by more than one SdBaseFile object
  506. * of file corruption may occur.
  507. *
  508. * \note Directory files must be opened read only. Write and truncation is
  509. * not allowed for directory files.
  510. *
  511. * \return true for success, false for failure.
  512. * Reasons for failure include this file is already open, \a dirFile is not
  513. * a directory, \a path is invalid, the file does not exist
  514. * or can't be opened in the access mode specified by oflag.
  515. */
  516. bool SdBaseFile::open(SdBaseFile* dirFile, const char* path, uint8_t oflag) {
  517. uint8_t dname[11];
  518. SdBaseFile dir1, dir2;
  519. SdBaseFile *parent = dirFile, *sub = &dir1;
  520. if (!dirFile || isOpen()) return false;
  521. if (*path == '/') { // Path starts with '/'
  522. if (!dirFile->isRoot()) { // Is the passed dirFile the root?
  523. if (!dir2.openRoot(dirFile->vol_)) return false; // Get the root in dir2, if possible
  524. parent = &dir2; // Change 'parent' to point at the root dir
  525. }
  526. while (*path == '/') path++; // Skip all leading slashes
  527. }
  528. for (;;) {
  529. if (!make83Name(path, dname, &path)) return false;
  530. while (*path == '/') path++;
  531. if (!*path) break;
  532. if (!sub->open(parent, dname, O_READ)) return false;
  533. if (parent != dirFile) parent->close();
  534. parent = sub;
  535. sub = parent != &dir1 ? &dir1 : &dir2;
  536. }
  537. return open(parent, dname, oflag);
  538. }
  539. // open with filename in dname
  540. bool SdBaseFile::open(SdBaseFile* dirFile, const uint8_t dname[11], uint8_t oflag) {
  541. bool emptyFound = false, fileFound = false;
  542. uint8_t index;
  543. dir_t* p;
  544. vol_ = dirFile->vol_;
  545. dirFile->rewind();
  546. // search for file
  547. while (dirFile->curPosition_ < dirFile->fileSize_) {
  548. index = 0xF & (dirFile->curPosition_ >> 5);
  549. p = dirFile->readDirCache();
  550. if (!p) return false;
  551. if (p->name[0] == DIR_NAME_FREE || p->name[0] == DIR_NAME_DELETED) {
  552. // remember first empty slot
  553. if (!emptyFound) {
  554. dirBlock_ = dirFile->vol_->cacheBlockNumber();
  555. dirIndex_ = index;
  556. emptyFound = true;
  557. }
  558. // done if no entries follow
  559. if (p->name[0] == DIR_NAME_FREE) break;
  560. }
  561. else if (!memcmp(dname, p->name, 11)) {
  562. fileFound = true;
  563. break;
  564. }
  565. }
  566. if (fileFound) {
  567. // don't open existing file if O_EXCL
  568. if (oflag & O_EXCL) return false;
  569. }
  570. else {
  571. // don't create unless O_CREAT and O_WRITE
  572. if ((oflag & (O_CREAT | O_WRITE)) != (O_CREAT | O_WRITE)) return false;
  573. if (emptyFound) {
  574. index = dirIndex_;
  575. p = cacheDirEntry(SdVolume::CACHE_FOR_WRITE);
  576. if (!p) return false;
  577. }
  578. else {
  579. if (dirFile->type_ == FAT_FILE_TYPE_ROOT_FIXED) return false;
  580. // add and zero cluster for dirFile - first cluster is in cache for write
  581. if (!dirFile->addDirCluster()) return false;
  582. // use first entry in cluster
  583. p = dirFile->vol_->cache()->dir;
  584. index = 0;
  585. }
  586. // initialize as empty file
  587. memset(p, 0, sizeof(*p));
  588. memcpy(p->name, dname, 11);
  589. // set timestamps
  590. if (dateTime_) {
  591. // call user date/time function
  592. dateTime_(&p->creationDate, &p->creationTime);
  593. }
  594. else {
  595. // use default date/time
  596. p->creationDate = FAT_DEFAULT_DATE;
  597. p->creationTime = FAT_DEFAULT_TIME;
  598. }
  599. p->lastAccessDate = p->creationDate;
  600. p->lastWriteDate = p->creationDate;
  601. p->lastWriteTime = p->creationTime;
  602. // write entry to SD
  603. if (!dirFile->vol_->cacheFlush()) return false;
  604. }
  605. // open entry in cache
  606. return openCachedEntry(index, oflag);
  607. }
  608. /**
  609. * Open a file by index.
  610. *
  611. * \param[in] dirFile An open SdFat instance for the directory.
  612. *
  613. * \param[in] index The \a index of the directory entry for the file to be
  614. * opened. The value for \a index is (directory file position)/32.
  615. *
  616. * \param[in] oflag Values for \a oflag are constructed by a bitwise-inclusive
  617. * OR of flags O_READ, O_WRITE, O_TRUNC, and O_SYNC.
  618. *
  619. * See open() by path for definition of flags.
  620. * \return true for success or false for failure.
  621. */
  622. bool SdBaseFile::open(SdBaseFile* dirFile, uint16_t index, uint8_t oflag) {
  623. dir_t* p;
  624. vol_ = dirFile->vol_;
  625. // error if already open
  626. if (isOpen() || !dirFile) return false;
  627. // don't open existing file if O_EXCL - user call error
  628. if (oflag & O_EXCL) return false;
  629. // seek to location of entry
  630. if (!dirFile->seekSet(32 * index)) return false;
  631. // read entry into cache
  632. p = dirFile->readDirCache();
  633. if (!p) return false;
  634. // error if empty slot or '.' or '..'
  635. if (p->name[0] == DIR_NAME_FREE ||
  636. p->name[0] == DIR_NAME_DELETED || p->name[0] == '.') {
  637. return false;
  638. }
  639. // open cached entry
  640. return openCachedEntry(index & 0xF, oflag);
  641. }
  642. // open a cached directory entry. Assumes vol_ is initialized
  643. bool SdBaseFile::openCachedEntry(uint8_t dirIndex, uint8_t oflag) {
  644. dir_t* p;
  645. #if ENABLED(SDCARD_READONLY)
  646. if (oflag & (O_WRITE | O_CREAT | O_TRUNC)) goto FAIL;
  647. #endif
  648. // location of entry in cache
  649. p = &vol_->cache()->dir[dirIndex];
  650. // write or truncate is an error for a directory or read-only file
  651. if (p->attributes & (DIR_ATT_READ_ONLY | DIR_ATT_DIRECTORY)) {
  652. if (oflag & (O_WRITE | O_TRUNC)) goto FAIL;
  653. }
  654. // remember location of directory entry on SD
  655. dirBlock_ = vol_->cacheBlockNumber();
  656. dirIndex_ = dirIndex;
  657. // copy first cluster number for directory fields
  658. firstCluster_ = (uint32_t)p->firstClusterHigh << 16;
  659. firstCluster_ |= p->firstClusterLow;
  660. // make sure it is a normal file or subdirectory
  661. if (DIR_IS_FILE(p)) {
  662. fileSize_ = p->fileSize;
  663. type_ = FAT_FILE_TYPE_NORMAL;
  664. }
  665. else if (DIR_IS_SUBDIR(p)) {
  666. if (!vol_->chainSize(firstCluster_, &fileSize_)) goto FAIL;
  667. type_ = FAT_FILE_TYPE_SUBDIR;
  668. }
  669. else
  670. goto FAIL;
  671. // save open flags for read/write
  672. flags_ = oflag & F_OFLAG;
  673. // set to start of file
  674. curCluster_ = 0;
  675. curPosition_ = 0;
  676. if ((oflag & O_TRUNC) && !truncate(0)) return false;
  677. return oflag & O_AT_END ? seekEnd(0) : true;
  678. FAIL:
  679. type_ = FAT_FILE_TYPE_CLOSED;
  680. return false;
  681. }
  682. /**
  683. * Open the next file or subdirectory in a directory.
  684. *
  685. * \param[in] dirFile An open SdFat instance for the directory containing the
  686. * file to be opened.
  687. *
  688. * \param[in] oflag Values for \a oflag are constructed by a bitwise-inclusive
  689. * OR of flags O_READ, O_WRITE, O_TRUNC, and O_SYNC.
  690. *
  691. * See open() by path for definition of flags.
  692. * \return true for success or false for failure.
  693. */
  694. bool SdBaseFile::openNext(SdBaseFile* dirFile, uint8_t oflag) {
  695. dir_t* p;
  696. uint8_t index;
  697. if (!dirFile) return false;
  698. // error if already open
  699. if (isOpen()) return false;
  700. vol_ = dirFile->vol_;
  701. while (1) {
  702. index = 0xF & (dirFile->curPosition_ >> 5);
  703. // read entry into cache
  704. p = dirFile->readDirCache();
  705. if (!p) return false;
  706. // done if last entry
  707. if (p->name[0] == DIR_NAME_FREE) return false;
  708. // skip empty slot or '.' or '..'
  709. if (p->name[0] == DIR_NAME_DELETED || p->name[0] == '.') {
  710. continue;
  711. }
  712. // must be file or dir
  713. if (DIR_IS_FILE_OR_SUBDIR(p)) {
  714. return openCachedEntry(index, oflag);
  715. }
  716. }
  717. return false;
  718. }
  719. #if 0
  720. /**
  721. * Open a directory's parent directory.
  722. *
  723. * \param[in] dir Parent of this directory will be opened. Must not be root.
  724. *
  725. * \return true for success, false for failure.
  726. */
  727. bool SdBaseFile::openParent(SdBaseFile* dir) {
  728. dir_t entry;
  729. dir_t* p;
  730. SdBaseFile file;
  731. uint32_t c;
  732. uint32_t cluster;
  733. uint32_t lbn;
  734. // error if already open or dir is root or dir is not a directory
  735. if (isOpen() || !dir || dir->isRoot() || !dir->isDir()) return false;
  736. vol_ = dir->vol_;
  737. // position to '..'
  738. if (!dir->seekSet(32)) return false;
  739. // read '..' entry
  740. if (dir->read(&entry, sizeof(entry)) != 32) return false;
  741. // verify it is '..'
  742. if (entry.name[0] != '.' || entry.name[1] != '.') return false;
  743. // start cluster for '..'
  744. cluster = entry.firstClusterLow;
  745. cluster |= (uint32_t)entry.firstClusterHigh << 16;
  746. if (cluster == 0) return openRoot(vol_);
  747. // start block for '..'
  748. lbn = vol_->clusterStartBlock(cluster);
  749. // first block of parent dir
  750. if (!vol_->cacheRawBlock(lbn, SdVolume::CACHE_FOR_READ)) return false;
  751. p = &vol_->cacheBuffer_.dir[1];
  752. // verify name for '../..'
  753. if (p->name[0] != '.' || p->name[1] != '.') return false;
  754. // '..' is pointer to first cluster of parent. open '../..' to find parent
  755. if (p->firstClusterHigh == 0 && p->firstClusterLow == 0) {
  756. if (!file.openRoot(dir->volume())) return false;
  757. }
  758. else if (!file.openCachedEntry(1, O_READ))
  759. return false;
  760. // search for parent in '../..'
  761. do {
  762. if (file.readDir(&entry, nullptr) != 32) return false;
  763. c = entry.firstClusterLow;
  764. c |= (uint32_t)entry.firstClusterHigh << 16;
  765. } while (c != cluster);
  766. // open parent
  767. return open(&file, file.curPosition() / 32 - 1, O_READ);
  768. }
  769. #endif
  770. /**
  771. * Open a volume's root directory.
  772. *
  773. * \param[in] vol The FAT volume containing the root directory to be opened.
  774. *
  775. * \return true for success, false for failure.
  776. * Reasons for failure include the file is already open, the FAT volume has
  777. * not been initialized or it a FAT12 volume.
  778. */
  779. bool SdBaseFile::openRoot(SdVolume* vol) {
  780. // error if file is already open
  781. if (isOpen()) return false;
  782. if (vol->fatType() == 16 || (FAT12_SUPPORT && vol->fatType() == 12)) {
  783. type_ = FAT_FILE_TYPE_ROOT_FIXED;
  784. firstCluster_ = 0;
  785. fileSize_ = 32 * vol->rootDirEntryCount();
  786. }
  787. else if (vol->fatType() == 32) {
  788. type_ = FAT_FILE_TYPE_ROOT32;
  789. firstCluster_ = vol->rootDirStart();
  790. if (!vol->chainSize(firstCluster_, &fileSize_)) return false;
  791. }
  792. else // volume is not initialized, invalid, or FAT12 without support
  793. return false;
  794. vol_ = vol;
  795. // read only
  796. flags_ = O_READ;
  797. // set to start of file
  798. curCluster_ = curPosition_ = 0;
  799. // root has no directory entry
  800. dirBlock_ = dirIndex_ = 0;
  801. return true;
  802. }
  803. /**
  804. * Return the next available byte without consuming it.
  805. *
  806. * \return The byte if no error and not at eof else -1;
  807. */
  808. int SdBaseFile::peek() {
  809. filepos_t pos;
  810. getpos(&pos);
  811. int c = read();
  812. if (c >= 0) setpos(&pos);
  813. return c;
  814. }
  815. // print uint8_t with width 2
  816. static void print2u(const uint8_t v) {
  817. if (v < 10) SERIAL_CHAR('0');
  818. SERIAL_ECHO(int(v));
  819. }
  820. /**
  821. * %Print a directory date field to Serial.
  822. *
  823. * Format is yyyy-mm-dd.
  824. *
  825. * \param[in] fatDate The date field from a directory entry.
  826. */
  827. /**
  828. * %Print a directory date field.
  829. *
  830. * Format is yyyy-mm-dd.
  831. *
  832. * \param[in] pr Print stream for output.
  833. * \param[in] fatDate The date field from a directory entry.
  834. */
  835. void SdBaseFile::printFatDate(uint16_t fatDate) {
  836. SERIAL_ECHO(FAT_YEAR(fatDate));
  837. SERIAL_CHAR('-');
  838. print2u(FAT_MONTH(fatDate));
  839. SERIAL_CHAR('-');
  840. print2u(FAT_DAY(fatDate));
  841. }
  842. /**
  843. * %Print a directory time field.
  844. *
  845. * Format is hh:mm:ss.
  846. *
  847. * \param[in] pr Print stream for output.
  848. * \param[in] fatTime The time field from a directory entry.
  849. */
  850. void SdBaseFile::printFatTime(uint16_t fatTime) {
  851. print2u(FAT_HOUR(fatTime));
  852. SERIAL_CHAR(':');
  853. print2u(FAT_MINUTE(fatTime));
  854. SERIAL_CHAR(':');
  855. print2u(FAT_SECOND(fatTime));
  856. }
  857. /**
  858. * Print a file's name to Serial
  859. *
  860. * \return true for success, false for failure.
  861. */
  862. bool SdBaseFile::printName() {
  863. char name[FILENAME_LENGTH];
  864. if (!getDosName(name)) return false;
  865. SERIAL_ECHO(name);
  866. return true;
  867. }
  868. /**
  869. * Read the next byte from a file.
  870. *
  871. * \return For success read returns the next byte in the file as an int.
  872. * If an error occurs or end of file is reached -1 is returned.
  873. */
  874. int16_t SdBaseFile::read() {
  875. uint8_t b;
  876. return read(&b, 1) == 1 ? b : -1;
  877. }
  878. /**
  879. * Read data from a file starting at the current position.
  880. *
  881. * \param[out] buf Pointer to the location that will receive the data.
  882. *
  883. * \param[in] nbyte Maximum number of bytes to read.
  884. *
  885. * \return For success read() returns the number of bytes read.
  886. * A value less than \a nbyte, including zero, will be returned
  887. * if end of file is reached.
  888. * If an error occurs, read() returns -1. Possible errors include
  889. * read() called before a file has been opened, corrupt file system
  890. * or an I/O error occurred.
  891. */
  892. int16_t SdBaseFile::read(void* buf, uint16_t nbyte) {
  893. uint8_t* dst = reinterpret_cast<uint8_t*>(buf);
  894. uint16_t offset, toRead;
  895. uint32_t block; // raw device block number
  896. // error if not open or write only
  897. if (!isOpen() || !(flags_ & O_READ)) return -1;
  898. // max bytes left in file
  899. NOMORE(nbyte, fileSize_ - curPosition_);
  900. // amount left to read
  901. toRead = nbyte;
  902. while (toRead > 0) {
  903. offset = curPosition_ & 0x1FF; // offset in block
  904. if (type_ == FAT_FILE_TYPE_ROOT_FIXED) {
  905. block = vol_->rootDirStart() + (curPosition_ >> 9);
  906. }
  907. else {
  908. uint8_t blockOfCluster = vol_->blockOfCluster(curPosition_);
  909. if (offset == 0 && blockOfCluster == 0) {
  910. // start of new cluster
  911. if (curPosition_ == 0)
  912. curCluster_ = firstCluster_; // use first cluster in file
  913. else if (!vol_->fatGet(curCluster_, &curCluster_)) // get next cluster from FAT
  914. return -1;
  915. }
  916. block = vol_->clusterStartBlock(curCluster_) + blockOfCluster;
  917. }
  918. uint16_t n = toRead;
  919. // amount to be read from current block
  920. NOMORE(n, 512 - offset);
  921. // no buffering needed if n == 512
  922. if (n == 512 && block != vol_->cacheBlockNumber()) {
  923. if (!vol_->readBlock(block, dst)) return -1;
  924. }
  925. else {
  926. // read block to cache and copy data to caller
  927. if (!vol_->cacheRawBlock(block, SdVolume::CACHE_FOR_READ)) return -1;
  928. uint8_t* src = vol_->cache()->data + offset;
  929. memcpy(dst, src, n);
  930. }
  931. dst += n;
  932. curPosition_ += n;
  933. toRead -= n;
  934. }
  935. return nbyte;
  936. }
  937. /**
  938. * Read the next entry in a directory.
  939. *
  940. * \param[out] dir The dir_t struct that will receive the data.
  941. *
  942. * \return For success readDir() returns the number of bytes read.
  943. * A value of zero will be returned if end of file is reached.
  944. * If an error occurs, readDir() returns -1. Possible errors include
  945. * readDir() called before a directory has been opened, this is not
  946. * a directory file or an I/O error occurred.
  947. */
  948. int8_t SdBaseFile::readDir(dir_t* dir, char* longFilename) {
  949. int16_t n;
  950. // if not a directory file or miss-positioned return an error
  951. if (!isDir() || (0x1F & curPosition_)) return -1;
  952. // If we have a longFilename buffer, mark it as invalid.
  953. // If a long filename is found it will be filled automatically.
  954. if (longFilename) longFilename[0] = '\0';
  955. while (1) {
  956. n = read(dir, sizeof(dir_t));
  957. if (n != sizeof(dir_t)) return n ? -1 : 0;
  958. // last entry if DIR_NAME_FREE
  959. if (dir->name[0] == DIR_NAME_FREE) return 0;
  960. // skip deleted entry and entry for . and ..
  961. if (dir->name[0] == DIR_NAME_DELETED || dir->name[0] == '.') {
  962. if (longFilename) longFilename[0] = '\0'; // Invalidate erased file long name, if any
  963. continue;
  964. }
  965. // Fill the long filename if we have a long filename entry.
  966. // Long filename entries are stored before the short filename.
  967. if (longFilename && DIR_IS_LONG_NAME(dir)) {
  968. vfat_t* VFAT = (vfat_t*)dir;
  969. // Sanity-check the VFAT entry. The first cluster is always set to zero. And the sequence number should be higher than 0
  970. if (VFAT->firstClusterLow == 0) {
  971. const uint8_t seq = VFAT->sequenceNumber & 0x1F;
  972. if (WITHIN(seq, 1, MAX_VFAT_ENTRIES)) {
  973. // TODO: Store the filename checksum to verify if a long-filename-unaware system modified the file table.
  974. n = (seq - 1) * (FILENAME_LENGTH);
  975. LOOP_L_N(i, FILENAME_LENGTH)
  976. longFilename[n + i] = (i < 5) ? VFAT->name1[i] : (i < 11) ? VFAT->name2[i - 5] : VFAT->name3[i - 11];
  977. // If this VFAT entry is the last one, add a NUL terminator at the end of the string
  978. if (VFAT->sequenceNumber & 0x40) longFilename[n + FILENAME_LENGTH] = '\0';
  979. }
  980. }
  981. }
  982. // Return if normal file or subdirectory
  983. if (DIR_IS_FILE_OR_SUBDIR(dir)) return n;
  984. }
  985. }
  986. // Read next directory entry into the cache
  987. // Assumes file is correctly positioned
  988. dir_t* SdBaseFile::readDirCache() {
  989. uint8_t i;
  990. // error if not directory
  991. if (!isDir()) return 0;
  992. // index of entry in cache
  993. i = (curPosition_ >> 5) & 0xF;
  994. // use read to locate and cache block
  995. if (read() < 0) return 0;
  996. // advance to next entry
  997. curPosition_ += 31;
  998. // return pointer to entry
  999. return vol_->cache()->dir + i;
  1000. }
  1001. /**
  1002. * Remove a file.
  1003. *
  1004. * The directory entry and all data for the file are deleted.
  1005. *
  1006. * \note This function should not be used to delete the 8.3 version of a
  1007. * file that has a long name. For example if a file has the long name
  1008. * "New Text Document.txt" you should not delete the 8.3 name "NEWTEX~1.TXT".
  1009. *
  1010. * \return true for success, false for failure.
  1011. * Reasons for failure include the file read-only, is a directory,
  1012. * or an I/O error occurred.
  1013. */
  1014. bool SdBaseFile::remove() {
  1015. if (ENABLED(SDCARD_READONLY)) return false;
  1016. dir_t* d;
  1017. // free any clusters - will fail if read-only or directory
  1018. if (!truncate(0)) return false;
  1019. // cache directory entry
  1020. d = cacheDirEntry(SdVolume::CACHE_FOR_WRITE);
  1021. if (!d) return false;
  1022. // mark entry deleted
  1023. d->name[0] = DIR_NAME_DELETED;
  1024. // set this file closed
  1025. type_ = FAT_FILE_TYPE_CLOSED;
  1026. // write entry to SD
  1027. return vol_->cacheFlush();
  1028. return true;
  1029. }
  1030. /**
  1031. * Remove a file.
  1032. *
  1033. * The directory entry and all data for the file are deleted.
  1034. *
  1035. * \param[in] dirFile The directory that contains the file.
  1036. * \param[in] path Path for the file to be removed.
  1037. *
  1038. * \note This function should not be used to delete the 8.3 version of a
  1039. * file that has a long name. For example if a file has the long name
  1040. * "New Text Document.txt" you should not delete the 8.3 name "NEWTEX~1.TXT".
  1041. *
  1042. * \return true for success, false for failure.
  1043. * Reasons for failure include the file is a directory, is read only,
  1044. * \a dirFile is not a directory, \a path is not found
  1045. * or an I/O error occurred.
  1046. */
  1047. bool SdBaseFile::remove(SdBaseFile* dirFile, const char* path) {
  1048. if (ENABLED(SDCARD_READONLY)) return false;
  1049. SdBaseFile file;
  1050. return file.open(dirFile, path, O_WRITE) ? file.remove() : false;
  1051. }
  1052. /**
  1053. * Rename a file or subdirectory.
  1054. *
  1055. * \param[in] dirFile Directory for the new path.
  1056. * \param[in] newPath New path name for the file/directory.
  1057. *
  1058. * \return true for success, false for failure.
  1059. * Reasons for failure include \a dirFile is not open or is not a directory
  1060. * file, newPath is invalid or already exists, or an I/O error occurs.
  1061. */
  1062. bool SdBaseFile::rename(SdBaseFile* dirFile, const char* newPath) {
  1063. if (ENABLED(SDCARD_READONLY)) return false;
  1064. dir_t entry;
  1065. uint32_t dirCluster = 0;
  1066. SdBaseFile file;
  1067. dir_t* d;
  1068. // must be an open file or subdirectory
  1069. if (!(isFile() || isSubDir())) return false;
  1070. // can't move file
  1071. if (vol_ != dirFile->vol_) return false;
  1072. // sync() and cache directory entry
  1073. sync();
  1074. d = cacheDirEntry(SdVolume::CACHE_FOR_WRITE);
  1075. if (!d) return false;
  1076. // save directory entry
  1077. memcpy(&entry, d, sizeof(entry));
  1078. // mark entry deleted
  1079. d->name[0] = DIR_NAME_DELETED;
  1080. // make directory entry for new path
  1081. if (isFile()) {
  1082. if (!file.open(dirFile, newPath, O_CREAT | O_EXCL | O_WRITE)) {
  1083. goto restore;
  1084. }
  1085. }
  1086. else {
  1087. // don't create missing path prefix components
  1088. if (!file.mkdir(dirFile, newPath, false)) {
  1089. goto restore;
  1090. }
  1091. // save cluster containing new dot dot
  1092. dirCluster = file.firstCluster_;
  1093. }
  1094. // change to new directory entry
  1095. dirBlock_ = file.dirBlock_;
  1096. dirIndex_ = file.dirIndex_;
  1097. // mark closed to avoid possible destructor close call
  1098. file.type_ = FAT_FILE_TYPE_CLOSED;
  1099. // cache new directory entry
  1100. d = cacheDirEntry(SdVolume::CACHE_FOR_WRITE);
  1101. if (!d) return false;
  1102. // copy all but name field to new directory entry
  1103. memcpy(&d->attributes, &entry.attributes, sizeof(entry) - sizeof(d->name));
  1104. // update dot dot if directory
  1105. if (dirCluster) {
  1106. // get new dot dot
  1107. uint32_t block = vol_->clusterStartBlock(dirCluster);
  1108. if (!vol_->cacheRawBlock(block, SdVolume::CACHE_FOR_READ)) return false;
  1109. memcpy(&entry, &vol_->cache()->dir[1], sizeof(entry));
  1110. // free unused cluster
  1111. if (!vol_->freeChain(dirCluster)) return false;
  1112. // store new dot dot
  1113. block = vol_->clusterStartBlock(firstCluster_);
  1114. if (!vol_->cacheRawBlock(block, SdVolume::CACHE_FOR_WRITE)) return false;
  1115. memcpy(&vol_->cache()->dir[1], &entry, sizeof(entry));
  1116. }
  1117. return vol_->cacheFlush();
  1118. restore:
  1119. if ((d = cacheDirEntry(SdVolume::CACHE_FOR_WRITE))) {
  1120. // restore entry
  1121. d->name[0] = entry.name[0];
  1122. vol_->cacheFlush();
  1123. }
  1124. return false;
  1125. }
  1126. /**
  1127. * Remove a directory file.
  1128. *
  1129. * The directory file will be removed only if it is empty and is not the
  1130. * root directory. rmdir() follows DOS and Windows and ignores the
  1131. * read-only attribute for the directory.
  1132. *
  1133. * \note This function should not be used to delete the 8.3 version of a
  1134. * directory that has a long name. For example if a directory has the
  1135. * long name "New folder" you should not delete the 8.3 name "NEWFOL~1".
  1136. *
  1137. * \return true for success, false for failure.
  1138. * Reasons for failure include the file is not a directory, is the root
  1139. * directory, is not empty, or an I/O error occurred.
  1140. */
  1141. bool SdBaseFile::rmdir() {
  1142. if (ENABLED(SDCARD_READONLY)) return false;
  1143. // must be open subdirectory
  1144. if (!isSubDir()) return false;
  1145. rewind();
  1146. // make sure directory is empty
  1147. while (curPosition_ < fileSize_) {
  1148. dir_t* p = readDirCache();
  1149. if (!p) return false;
  1150. // done if past last used entry
  1151. if (p->name[0] == DIR_NAME_FREE) break;
  1152. // skip empty slot, '.' or '..'
  1153. if (p->name[0] == DIR_NAME_DELETED || p->name[0] == '.') continue;
  1154. // error not empty
  1155. if (DIR_IS_FILE_OR_SUBDIR(p)) return false;
  1156. }
  1157. // convert empty directory to normal file for remove
  1158. type_ = FAT_FILE_TYPE_NORMAL;
  1159. flags_ |= O_WRITE;
  1160. return remove();
  1161. }
  1162. /**
  1163. * Recursively delete a directory and all contained files.
  1164. *
  1165. * This is like the Unix/Linux 'rm -rf *' if called with the root directory
  1166. * hence the name.
  1167. *
  1168. * Warning - This will remove all contents of the directory including
  1169. * subdirectories. The directory will then be removed if it is not root.
  1170. * The read-only attribute for files will be ignored.
  1171. *
  1172. * \note This function should not be used to delete the 8.3 version of
  1173. * a directory that has a long name. See remove() and rmdir().
  1174. *
  1175. * \return true for success, false for failure.
  1176. */
  1177. bool SdBaseFile::rmRfStar() {
  1178. if (ENABLED(SDCARD_READONLY)) return false;
  1179. uint32_t index;
  1180. SdBaseFile f;
  1181. rewind();
  1182. while (curPosition_ < fileSize_) {
  1183. // remember position
  1184. index = curPosition_ / 32;
  1185. dir_t* p = readDirCache();
  1186. if (!p) return false;
  1187. // done if past last entry
  1188. if (p->name[0] == DIR_NAME_FREE) break;
  1189. // skip empty slot or '.' or '..'
  1190. if (p->name[0] == DIR_NAME_DELETED || p->name[0] == '.') continue;
  1191. // skip if part of long file name or volume label in root
  1192. if (!DIR_IS_FILE_OR_SUBDIR(p)) continue;
  1193. if (!f.open(this, index, O_READ)) return false;
  1194. if (f.isSubDir()) {
  1195. // recursively delete
  1196. if (!f.rmRfStar()) return false;
  1197. }
  1198. else {
  1199. // ignore read-only
  1200. f.flags_ |= O_WRITE;
  1201. if (!f.remove()) return false;
  1202. }
  1203. // position to next entry if required
  1204. if (curPosition_ != (32 * (index + 1))) {
  1205. if (!seekSet(32 * (index + 1))) return false;
  1206. }
  1207. }
  1208. // don't try to delete root
  1209. if (!isRoot()) {
  1210. if (!rmdir()) return false;
  1211. }
  1212. return true;
  1213. }
  1214. /**
  1215. * Create a file object and open it in the current working directory.
  1216. *
  1217. * \param[in] path A path with a valid 8.3 DOS name for a file to be opened.
  1218. *
  1219. * \param[in] oflag Values for \a oflag are constructed by a bitwise-inclusive
  1220. * OR of open flags. see SdBaseFile::open(SdBaseFile*, const char*, uint8_t).
  1221. */
  1222. SdBaseFile::SdBaseFile(const char* path, uint8_t oflag) {
  1223. type_ = FAT_FILE_TYPE_CLOSED;
  1224. writeError = false;
  1225. open(path, oflag);
  1226. }
  1227. /**
  1228. * Sets a file's position.
  1229. *
  1230. * \param[in] pos The new position in bytes from the beginning of the file.
  1231. *
  1232. * \return true for success, false for failure.
  1233. */
  1234. bool SdBaseFile::seekSet(const uint32_t pos) {
  1235. uint32_t nCur, nNew;
  1236. // error if file not open or seek past end of file
  1237. if (!isOpen() || pos > fileSize_) return false;
  1238. if (type_ == FAT_FILE_TYPE_ROOT_FIXED) {
  1239. curPosition_ = pos;
  1240. return true;
  1241. }
  1242. if (pos == 0) {
  1243. curCluster_ = curPosition_ = 0; // set position to start of file
  1244. return true;
  1245. }
  1246. // calculate cluster index for cur and new position
  1247. nCur = (curPosition_ - 1) >> (vol_->clusterSizeShift_ + 9);
  1248. nNew = (pos - 1) >> (vol_->clusterSizeShift_ + 9);
  1249. if (nNew < nCur || curPosition_ == 0)
  1250. curCluster_ = firstCluster_; // must follow chain from first cluster
  1251. else
  1252. nNew -= nCur; // advance from curPosition
  1253. while (nNew--)
  1254. if (!vol_->fatGet(curCluster_, &curCluster_)) return false;
  1255. curPosition_ = pos;
  1256. return true;
  1257. }
  1258. void SdBaseFile::setpos(filepos_t* pos) {
  1259. curPosition_ = pos->position;
  1260. curCluster_ = pos->cluster;
  1261. }
  1262. /**
  1263. * The sync() call causes all modified data and directory fields
  1264. * to be written to the storage device.
  1265. *
  1266. * \return true for success, false for failure.
  1267. * Reasons for failure include a call to sync() before a file has been
  1268. * opened or an I/O error.
  1269. */
  1270. bool SdBaseFile::sync() {
  1271. // only allow open files and directories
  1272. if (ENABLED(SDCARD_READONLY) || !isOpen()) goto FAIL;
  1273. if (flags_ & F_FILE_DIR_DIRTY) {
  1274. dir_t* d = cacheDirEntry(SdVolume::CACHE_FOR_WRITE);
  1275. // check for deleted by another open file object
  1276. if (!d || d->name[0] == DIR_NAME_DELETED) goto FAIL;
  1277. // do not set filesize for dir files
  1278. if (!isDir()) d->fileSize = fileSize_;
  1279. // update first cluster fields
  1280. d->firstClusterLow = firstCluster_ & 0xFFFF;
  1281. d->firstClusterHigh = firstCluster_ >> 16;
  1282. // set modify time if user supplied a callback date/time function
  1283. if (dateTime_) {
  1284. dateTime_(&d->lastWriteDate, &d->lastWriteTime);
  1285. d->lastAccessDate = d->lastWriteDate;
  1286. }
  1287. // clear directory dirty
  1288. flags_ &= ~F_FILE_DIR_DIRTY;
  1289. }
  1290. return vol_->cacheFlush();
  1291. FAIL:
  1292. writeError = true;
  1293. return false;
  1294. }
  1295. /**
  1296. * Copy a file's timestamps
  1297. *
  1298. * \param[in] file File to copy timestamps from.
  1299. *
  1300. * \note
  1301. * Modify and access timestamps may be overwritten if a date time callback
  1302. * function has been set by dateTimeCallback().
  1303. *
  1304. * \return true for success, false for failure.
  1305. */
  1306. bool SdBaseFile::timestamp(SdBaseFile* file) {
  1307. dir_t* d;
  1308. dir_t dir;
  1309. // get timestamps
  1310. if (!file->dirEntry(&dir)) return false;
  1311. // update directory fields
  1312. if (!sync()) return false;
  1313. d = cacheDirEntry(SdVolume::CACHE_FOR_WRITE);
  1314. if (!d) return false;
  1315. // copy timestamps
  1316. d->lastAccessDate = dir.lastAccessDate;
  1317. d->creationDate = dir.creationDate;
  1318. d->creationTime = dir.creationTime;
  1319. d->creationTimeTenths = dir.creationTimeTenths;
  1320. d->lastWriteDate = dir.lastWriteDate;
  1321. d->lastWriteTime = dir.lastWriteTime;
  1322. // write back entry
  1323. return vol_->cacheFlush();
  1324. }
  1325. /**
  1326. * Set a file's timestamps in its directory entry.
  1327. *
  1328. * \param[in] flags Values for \a flags are constructed by a bitwise-inclusive
  1329. * OR of flags from the following list
  1330. *
  1331. * T_ACCESS - Set the file's last access date.
  1332. *
  1333. * T_CREATE - Set the file's creation date and time.
  1334. *
  1335. * T_WRITE - Set the file's last write/modification date and time.
  1336. *
  1337. * \param[in] year Valid range 1980 - 2107 inclusive.
  1338. *
  1339. * \param[in] month Valid range 1 - 12 inclusive.
  1340. *
  1341. * \param[in] day Valid range 1 - 31 inclusive.
  1342. *
  1343. * \param[in] hour Valid range 0 - 23 inclusive.
  1344. *
  1345. * \param[in] minute Valid range 0 - 59 inclusive.
  1346. *
  1347. * \param[in] second Valid range 0 - 59 inclusive
  1348. *
  1349. * \note It is possible to set an invalid date since there is no check for
  1350. * the number of days in a month.
  1351. *
  1352. * \note
  1353. * Modify and access timestamps may be overwritten if a date time callback
  1354. * function has been set by dateTimeCallback().
  1355. *
  1356. * \return true for success, false for failure.
  1357. */
  1358. bool SdBaseFile::timestamp(uint8_t flags, uint16_t year, uint8_t month,
  1359. uint8_t day, uint8_t hour, uint8_t minute, uint8_t second) {
  1360. if (ENABLED(SDCARD_READONLY)) return false;
  1361. uint16_t dirDate, dirTime;
  1362. dir_t* d;
  1363. if (!isOpen()
  1364. || year < 1980
  1365. || year > 2107
  1366. || month < 1
  1367. || month > 12
  1368. || day < 1
  1369. || day > 31
  1370. || hour > 23
  1371. || minute > 59
  1372. || second > 59) {
  1373. return false;
  1374. }
  1375. // update directory entry
  1376. if (!sync()) return false;
  1377. d = cacheDirEntry(SdVolume::CACHE_FOR_WRITE);
  1378. if (!d) return false;
  1379. dirDate = FAT_DATE(year, month, day);
  1380. dirTime = FAT_TIME(hour, minute, second);
  1381. if (flags & T_ACCESS) {
  1382. d->lastAccessDate = dirDate;
  1383. }
  1384. if (flags & T_CREATE) {
  1385. d->creationDate = dirDate;
  1386. d->creationTime = dirTime;
  1387. // seems to be units of 1/100 second not 1/10 as Microsoft states
  1388. d->creationTimeTenths = second & 1 ? 100 : 0;
  1389. }
  1390. if (flags & T_WRITE) {
  1391. d->lastWriteDate = dirDate;
  1392. d->lastWriteTime = dirTime;
  1393. }
  1394. return vol_->cacheFlush();
  1395. }
  1396. /**
  1397. * Truncate a file to a specified length. The current file position
  1398. * will be maintained if it is less than or equal to \a length otherwise
  1399. * it will be set to end of file.
  1400. *
  1401. * \param[in] length The desired length for the file.
  1402. *
  1403. * \return true for success, false for failure.
  1404. * Reasons for failure include file is read only, file is a directory,
  1405. * \a length is greater than the current file size or an I/O error occurs.
  1406. */
  1407. bool SdBaseFile::truncate(uint32_t length) {
  1408. if (ENABLED(SDCARD_READONLY)) return false;
  1409. uint32_t newPos;
  1410. // error if not a normal file or read-only
  1411. if (!isFile() || !(flags_ & O_WRITE)) return false;
  1412. // error if length is greater than current size
  1413. if (length > fileSize_) return false;
  1414. // fileSize and length are zero - nothing to do
  1415. if (fileSize_ == 0) return true;
  1416. // remember position for seek after truncation
  1417. newPos = curPosition_ > length ? length : curPosition_;
  1418. // position to last cluster in truncated file
  1419. if (!seekSet(length)) return false;
  1420. if (length == 0) {
  1421. // free all clusters
  1422. if (!vol_->freeChain(firstCluster_)) return false;
  1423. firstCluster_ = 0;
  1424. }
  1425. else {
  1426. uint32_t toFree;
  1427. if (!vol_->fatGet(curCluster_, &toFree)) return false;
  1428. if (!vol_->isEOC(toFree)) {
  1429. // free extra clusters
  1430. if (!vol_->freeChain(toFree)) return false;
  1431. // current cluster is end of chain
  1432. if (!vol_->fatPutEOC(curCluster_)) return false;
  1433. }
  1434. }
  1435. fileSize_ = length;
  1436. // need to update directory entry
  1437. flags_ |= F_FILE_DIR_DIRTY;
  1438. if (!sync()) return false;
  1439. // set file to correct position
  1440. return seekSet(newPos);
  1441. }
  1442. /**
  1443. * Write data to an open file.
  1444. *
  1445. * \note Data is moved to the cache but may not be written to the
  1446. * storage device until sync() is called.
  1447. *
  1448. * \param[in] buf Pointer to the location of the data to be written.
  1449. *
  1450. * \param[in] nbyte Number of bytes to write.
  1451. *
  1452. * \return For success write() returns the number of bytes written, always
  1453. * \a nbyte. If an error occurs, write() returns -1. Possible errors
  1454. * include write() is called before a file has been opened, write is called
  1455. * for a read-only file, device is full, a corrupt file system or an I/O error.
  1456. */
  1457. int16_t SdBaseFile::write(const void* buf, uint16_t nbyte) {
  1458. #if ENABLED(SDCARD_READONLY)
  1459. writeError = true; return -1;
  1460. #endif
  1461. // convert void* to uint8_t* - must be before goto statements
  1462. const uint8_t* src = reinterpret_cast<const uint8_t*>(buf);
  1463. // number of bytes left to write - must be before goto statements
  1464. uint16_t nToWrite = nbyte;
  1465. // error if not a normal file or is read-only
  1466. if (!isFile() || !(flags_ & O_WRITE)) goto FAIL;
  1467. // seek to end of file if append flag
  1468. if ((flags_ & O_APPEND) && curPosition_ != fileSize_) {
  1469. if (!seekEnd()) goto FAIL;
  1470. }
  1471. while (nToWrite > 0) {
  1472. uint8_t blockOfCluster = vol_->blockOfCluster(curPosition_);
  1473. uint16_t blockOffset = curPosition_ & 0x1FF;
  1474. if (blockOfCluster == 0 && blockOffset == 0) {
  1475. // start of new cluster
  1476. if (curCluster_ == 0) {
  1477. if (firstCluster_ == 0) {
  1478. // allocate first cluster of file
  1479. if (!addCluster()) goto FAIL;
  1480. }
  1481. else {
  1482. curCluster_ = firstCluster_;
  1483. }
  1484. }
  1485. else {
  1486. uint32_t next;
  1487. if (!vol_->fatGet(curCluster_, &next)) goto FAIL;
  1488. if (vol_->isEOC(next)) {
  1489. // add cluster if at end of chain
  1490. if (!addCluster()) goto FAIL;
  1491. }
  1492. else {
  1493. curCluster_ = next;
  1494. }
  1495. }
  1496. }
  1497. // max space in block
  1498. uint16_t n = 512 - blockOffset;
  1499. // lesser of space and amount to write
  1500. NOMORE(n, nToWrite);
  1501. // block for data write
  1502. uint32_t block = vol_->clusterStartBlock(curCluster_) + blockOfCluster;
  1503. if (n == 512) {
  1504. // full block - don't need to use cache
  1505. if (vol_->cacheBlockNumber() == block) {
  1506. // invalidate cache if block is in cache
  1507. vol_->cacheSetBlockNumber(0xFFFFFFFF, false);
  1508. }
  1509. if (!vol_->writeBlock(block, src)) goto FAIL;
  1510. }
  1511. else {
  1512. if (blockOffset == 0 && curPosition_ >= fileSize_) {
  1513. // start of new block don't need to read into cache
  1514. if (!vol_->cacheFlush()) goto FAIL;
  1515. // set cache dirty and SD address of block
  1516. vol_->cacheSetBlockNumber(block, true);
  1517. }
  1518. else {
  1519. // rewrite part of block
  1520. if (!vol_->cacheRawBlock(block, SdVolume::CACHE_FOR_WRITE)) goto FAIL;
  1521. }
  1522. uint8_t* dst = vol_->cache()->data + blockOffset;
  1523. memcpy(dst, src, n);
  1524. }
  1525. curPosition_ += n;
  1526. src += n;
  1527. nToWrite -= n;
  1528. }
  1529. if (curPosition_ > fileSize_) {
  1530. // update fileSize and insure sync will update dir entry
  1531. fileSize_ = curPosition_;
  1532. flags_ |= F_FILE_DIR_DIRTY;
  1533. }
  1534. else if (dateTime_ && nbyte) {
  1535. // insure sync will update modified date and time
  1536. flags_ |= F_FILE_DIR_DIRTY;
  1537. }
  1538. if (flags_ & O_SYNC) {
  1539. if (!sync()) goto FAIL;
  1540. }
  1541. return nbyte;
  1542. FAIL:
  1543. // return for write error
  1544. writeError = true;
  1545. return -1;
  1546. }
  1547. #endif // SDSUPPORT