SdBaseFile.cpp 59 KB

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