My Marlin configs for Fabrikator Mini and CTC i3 Pro B
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

SdBaseFile.cpp 53KB

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