FatFile.cpp 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498
  1. /**
  2. * Copyright (c) 20011-2017 Bill Greiman
  3. * This file is part of the SdFat library for SD memory cards.
  4. *
  5. * MIT License
  6. *
  7. * Permission is hereby granted, free of charge, to any person obtaining a
  8. * copy of this software and associated documentation files (the "Software"),
  9. * to deal in the Software without restriction, including without limitation
  10. * the rights to use, copy, modify, merge, publish, distribute, sublicense,
  11. * and/or sell copies of the Software, and to permit persons to whom the
  12. * Software is furnished to do so, subject to the following conditions:
  13. *
  14. * The above copyright notice and this permission notice shall be included
  15. * in all copies or substantial portions of the Software.
  16. *
  17. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  18. * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  19. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  20. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  21. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  22. * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  23. * DEALINGS IN THE SOFTWARE.
  24. */
  25. #include "FatFile.h"
  26. #include "FatFileSystem.h"
  27. //------------------------------------------------------------------------------
  28. // Pointer to cwd directory.
  29. FatFile* FatFile::m_cwd = 0;
  30. // Callback function for date/time.
  31. void (*FatFile::m_dateTime)(uint16_t* date, uint16_t* time) = 0;
  32. //------------------------------------------------------------------------------
  33. // Add a cluster to a file.
  34. bool FatFile::addCluster() {
  35. m_flags |= F_FILE_DIR_DIRTY;
  36. return m_vol->allocateCluster(m_curCluster, &m_curCluster);
  37. }
  38. //------------------------------------------------------------------------------
  39. // Add a cluster to a directory file and zero the cluster.
  40. // Return with first block of cluster in the cache.
  41. bool FatFile::addDirCluster() {
  42. uint32_t block;
  43. cache_t* pc;
  44. if (isRootFixed()) {
  45. DBG_FAIL_MACRO;
  46. goto fail;
  47. }
  48. // max folder size
  49. if (m_curPosition >= 512UL*4095) {
  50. DBG_FAIL_MACRO;
  51. goto fail;
  52. }
  53. if (!addCluster()) {
  54. DBG_FAIL_MACRO;
  55. goto fail;
  56. }
  57. block = m_vol->clusterFirstBlock(m_curCluster);
  58. pc = m_vol->cacheFetchData(block, FatCache::CACHE_RESERVE_FOR_WRITE);
  59. if (!pc) {
  60. DBG_FAIL_MACRO;
  61. goto fail;
  62. }
  63. memset(pc, 0, 512);
  64. // zero rest of clusters
  65. for (uint8_t i = 1; i < m_vol->blocksPerCluster(); i++) {
  66. if (!m_vol->writeBlock(block + i, pc->data)) {
  67. DBG_FAIL_MACRO;
  68. goto fail;
  69. }
  70. }
  71. // Set position to EOF to avoid inconsistent curCluster/curPosition.
  72. m_curPosition += 512UL*m_vol->blocksPerCluster();
  73. return true;
  74. fail:
  75. return false;
  76. }
  77. //------------------------------------------------------------------------------
  78. // cache a file's directory entry
  79. // return pointer to cached entry or null for failure
  80. dir_t* FatFile::cacheDirEntry(uint8_t action) {
  81. cache_t* pc;
  82. pc = m_vol->cacheFetchData(m_dirBlock, action);
  83. if (!pc) {
  84. DBG_FAIL_MACRO;
  85. goto fail;
  86. }
  87. return pc->dir + (m_dirIndex & 0XF);
  88. fail:
  89. return 0;
  90. }
  91. //------------------------------------------------------------------------------
  92. bool FatFile::close() {
  93. bool rtn = sync();
  94. m_attr = FILE_ATTR_CLOSED;
  95. return rtn;
  96. }
  97. //------------------------------------------------------------------------------
  98. bool FatFile::contiguousRange(uint32_t* bgnBlock, uint32_t* endBlock) {
  99. // error if no blocks
  100. if (m_firstCluster == 0) {
  101. DBG_FAIL_MACRO;
  102. goto fail;
  103. }
  104. for (uint32_t c = m_firstCluster; ; c++) {
  105. uint32_t next;
  106. int8_t fg = m_vol->fatGet(c, &next);
  107. if (fg < 0) {
  108. DBG_FAIL_MACRO;
  109. goto fail;
  110. }
  111. // check for contiguous
  112. if (fg == 0 || next != (c + 1)) {
  113. // error if not end of chain
  114. if (fg) {
  115. DBG_FAIL_MACRO;
  116. goto fail;
  117. }
  118. *bgnBlock = m_vol->clusterFirstBlock(m_firstCluster);
  119. *endBlock = m_vol->clusterFirstBlock(c)
  120. + m_vol->blocksPerCluster() - 1;
  121. return true;
  122. }
  123. }
  124. fail:
  125. return false;
  126. }
  127. //------------------------------------------------------------------------------
  128. bool FatFile::createContiguous(FatFile* dirFile,
  129. const char* path, uint32_t size) {
  130. uint32_t count;
  131. // don't allow zero length file
  132. if (size == 0) {
  133. DBG_FAIL_MACRO;
  134. goto fail;
  135. }
  136. if (!open(dirFile, path, O_CREAT | O_EXCL | O_RDWR)) {
  137. DBG_FAIL_MACRO;
  138. goto fail;
  139. }
  140. // calculate number of clusters needed
  141. count = ((size - 1) >> (m_vol->clusterSizeShift() + 9)) + 1;
  142. // allocate clusters
  143. if (!m_vol->allocContiguous(count, &m_firstCluster)) {
  144. remove();
  145. DBG_FAIL_MACRO;
  146. goto fail;
  147. }
  148. m_fileSize = size;
  149. // insure sync() will update dir entry
  150. m_flags |= F_FILE_DIR_DIRTY;
  151. return sync();
  152. fail:
  153. return false;
  154. }
  155. //------------------------------------------------------------------------------
  156. bool FatFile::dirEntry(dir_t* dst) {
  157. dir_t* dir;
  158. // Make sure fields on device are correct.
  159. if (!sync()) {
  160. DBG_FAIL_MACRO;
  161. goto fail;
  162. }
  163. // read entry
  164. dir = cacheDirEntry(FatCache::CACHE_FOR_READ);
  165. if (!dir) {
  166. DBG_FAIL_MACRO;
  167. goto fail;
  168. }
  169. // copy to caller's struct
  170. memcpy(dst, dir, sizeof(dir_t));
  171. return true;
  172. fail:
  173. return false;
  174. }
  175. //------------------------------------------------------------------------------
  176. uint8_t FatFile::dirName(const dir_t* dir, char* name) {
  177. uint8_t j = 0;
  178. uint8_t lcBit = DIR_NT_LC_BASE;
  179. for (uint8_t i = 0; i < 11; i++) {
  180. if (dir->name[i] == ' ') {
  181. continue;
  182. }
  183. if (i == 8) {
  184. // Position bit for extension.
  185. lcBit = DIR_NT_LC_EXT;
  186. name[j++] = '.';
  187. }
  188. char c = dir->name[i];
  189. if ('A' <= c && c <= 'Z' && (lcBit & dir->reservedNT)) {
  190. c += 'a' - 'A';
  191. }
  192. name[j++] = c;
  193. }
  194. name[j] = 0;
  195. return j;
  196. }
  197. //------------------------------------------------------------------------------
  198. uint32_t FatFile::dirSize() {
  199. int8_t fg;
  200. if (!isDir()) {
  201. return 0;
  202. }
  203. if (isRootFixed()) {
  204. return 32*m_vol->rootDirEntryCount();
  205. }
  206. uint16_t n = 0;
  207. uint32_t c = isRoot32() ? m_vol->rootDirStart() : m_firstCluster;
  208. do {
  209. fg = m_vol->fatGet(c, &c);
  210. if (fg < 0 || n > 4095) {
  211. return 0;
  212. }
  213. n += m_vol->blocksPerCluster();
  214. } while (fg);
  215. return 512UL*n;
  216. }
  217. //------------------------------------------------------------------------------
  218. int16_t FatFile::fgets(char* str, int16_t num, char* delim) {
  219. char ch;
  220. int16_t n = 0;
  221. int16_t r = -1;
  222. while ((n + 1) < num && (r = read(&ch, 1)) == 1) {
  223. // delete CR
  224. if (ch == '\r') {
  225. continue;
  226. }
  227. str[n++] = ch;
  228. if (!delim) {
  229. if (ch == '\n') {
  230. break;
  231. }
  232. } else {
  233. if (strchr(delim, ch)) {
  234. break;
  235. }
  236. }
  237. }
  238. if (r < 0) {
  239. // read error
  240. return -1;
  241. }
  242. str[n] = '\0';
  243. return n;
  244. }
  245. //------------------------------------------------------------------------------
  246. void FatFile::getpos(FatPos_t* pos) {
  247. pos->position = m_curPosition;
  248. pos->cluster = m_curCluster;
  249. }
  250. //------------------------------------------------------------------------------
  251. bool FatFile::mkdir(FatFile* parent, const char* path, bool pFlag) {
  252. fname_t fname;
  253. FatFile tmpDir;
  254. if (isOpen() || !parent->isDir()) {
  255. DBG_FAIL_MACRO;
  256. goto fail;
  257. }
  258. if (isDirSeparator(*path)) {
  259. while (isDirSeparator(*path)) {
  260. path++;
  261. }
  262. if (!tmpDir.openRoot(parent->m_vol)) {
  263. DBG_FAIL_MACRO;
  264. goto fail;
  265. }
  266. parent = &tmpDir;
  267. }
  268. while (1) {
  269. if (!parsePathName(path, &fname, &path)) {
  270. DBG_FAIL_MACRO;
  271. goto fail;
  272. }
  273. if (!*path) {
  274. break;
  275. }
  276. if (!open(parent, &fname, O_READ)) {
  277. if (!pFlag || !mkdir(parent, &fname)) {
  278. DBG_FAIL_MACRO;
  279. goto fail;
  280. }
  281. }
  282. tmpDir = *this;
  283. parent = &tmpDir;
  284. close();
  285. }
  286. return mkdir(parent, &fname);
  287. fail:
  288. return false;
  289. }
  290. //------------------------------------------------------------------------------
  291. bool FatFile::mkdir(FatFile* parent, fname_t* fname) {
  292. uint32_t block;
  293. dir_t dot;
  294. dir_t* dir;
  295. cache_t* pc;
  296. if (!parent->isDir()) {
  297. DBG_FAIL_MACRO;
  298. goto fail;
  299. }
  300. // create a normal file
  301. if (!open(parent, fname, O_CREAT | O_EXCL | O_RDWR)) {
  302. DBG_FAIL_MACRO;
  303. goto fail;
  304. }
  305. // convert file to directory
  306. m_flags = O_READ;
  307. m_attr = FILE_ATTR_SUBDIR;
  308. // allocate and zero first cluster
  309. if (!addDirCluster()) {
  310. DBG_FAIL_MACRO;
  311. goto fail;
  312. }
  313. m_firstCluster = m_curCluster;
  314. // Set to start of dir
  315. rewind();
  316. // force entry to device
  317. if (!sync()) {
  318. DBG_FAIL_MACRO;
  319. goto fail;
  320. }
  321. // cache entry - should already be in cache due to sync() call
  322. dir = cacheDirEntry(FatCache::CACHE_FOR_WRITE);
  323. if (!dir) {
  324. DBG_FAIL_MACRO;
  325. goto fail;
  326. }
  327. // change directory entry attribute
  328. dir->attributes = DIR_ATT_DIRECTORY;
  329. // make entry for '.'
  330. memcpy(&dot, dir, sizeof(dot));
  331. dot.name[0] = '.';
  332. for (uint8_t i = 1; i < 11; i++) {
  333. dot.name[i] = ' ';
  334. }
  335. // cache block for '.' and '..'
  336. block = m_vol->clusterFirstBlock(m_firstCluster);
  337. pc = m_vol->cacheFetchData(block, FatCache::CACHE_FOR_WRITE);
  338. if (!pc) {
  339. DBG_FAIL_MACRO;
  340. goto fail;
  341. }
  342. // copy '.' to block
  343. memcpy(&pc->dir[0], &dot, sizeof(dot));
  344. // make entry for '..'
  345. dot.name[1] = '.';
  346. dot.firstClusterLow = parent->m_firstCluster & 0XFFFF;
  347. dot.firstClusterHigh = parent->m_firstCluster >> 16;
  348. // copy '..' to block
  349. memcpy(&pc->dir[1], &dot, sizeof(dot));
  350. // write first block
  351. return m_vol->cacheSync();
  352. fail:
  353. return false;
  354. }
  355. //------------------------------------------------------------------------------
  356. bool FatFile::open(FatFileSystem* fs, const char* path, uint8_t oflag) {
  357. return open(fs->vwd(), path, oflag);
  358. }
  359. //------------------------------------------------------------------------------
  360. bool FatFile::open(FatFile* dirFile, const char* path, uint8_t oflag) {
  361. FatFile tmpDir;
  362. fname_t fname;
  363. // error if already open
  364. if (isOpen() || !dirFile->isDir()) {
  365. DBG_FAIL_MACRO;
  366. goto fail;
  367. }
  368. if (isDirSeparator(*path)) {
  369. while (isDirSeparator(*path)) {
  370. path++;
  371. }
  372. if (*path == 0) {
  373. return openRoot(dirFile->m_vol);
  374. }
  375. if (!tmpDir.openRoot(dirFile->m_vol)) {
  376. DBG_FAIL_MACRO;
  377. goto fail;
  378. }
  379. dirFile = &tmpDir;
  380. }
  381. while (1) {
  382. if (!parsePathName(path, &fname, &path)) {
  383. DBG_FAIL_MACRO;
  384. goto fail;
  385. }
  386. if (*path == 0) {
  387. break;
  388. }
  389. if (!open(dirFile, &fname, O_READ)) {
  390. DBG_FAIL_MACRO;
  391. goto fail;
  392. }
  393. tmpDir = *this;
  394. dirFile = &tmpDir;
  395. close();
  396. }
  397. return open(dirFile, &fname, oflag);
  398. fail:
  399. return false;
  400. }
  401. //------------------------------------------------------------------------------
  402. bool FatFile::open(FatFile* dirFile, uint16_t index, uint8_t oflag) {
  403. uint8_t chksum = 0;
  404. uint8_t lfnOrd = 0;
  405. dir_t* dir;
  406. ldir_t*ldir;
  407. // Error if already open.
  408. if (isOpen() || !dirFile->isDir()) {
  409. DBG_FAIL_MACRO;
  410. goto fail;
  411. }
  412. // Don't open existing file if O_EXCL - user call error.
  413. if (oflag & O_EXCL) {
  414. DBG_FAIL_MACRO;
  415. goto fail;
  416. }
  417. if (index) {
  418. // Check for LFN.
  419. if (!dirFile->seekSet(32UL*(index -1))) {
  420. DBG_FAIL_MACRO;
  421. goto fail;
  422. }
  423. ldir = reinterpret_cast<ldir_t*>(dirFile->readDirCache());
  424. if (!ldir) {
  425. DBG_FAIL_MACRO;
  426. goto fail;
  427. }
  428. if (ldir->attr == DIR_ATT_LONG_NAME) {
  429. if (1 == (ldir->ord & 0X1F)) {
  430. chksum = ldir->chksum;
  431. // Use largest possible number.
  432. lfnOrd = index > 20 ? 20 : index;
  433. }
  434. }
  435. } else {
  436. dirFile->rewind();
  437. }
  438. // read entry into cache
  439. dir = dirFile->readDirCache();
  440. if (!dir) {
  441. DBG_FAIL_MACRO;
  442. goto fail;
  443. }
  444. // error if empty slot or '.' or '..'
  445. if (dir->name[0] == DIR_NAME_DELETED ||
  446. dir->name[0] == DIR_NAME_FREE ||
  447. dir->name[0] == '.') {
  448. DBG_FAIL_MACRO;
  449. goto fail;
  450. }
  451. if (lfnOrd && chksum != lfnChecksum(dir->name)) {
  452. DBG_FAIL_MACRO;
  453. goto fail;
  454. }
  455. // open cached entry
  456. if (!openCachedEntry(dirFile, index, oflag, lfnOrd)) {
  457. DBG_FAIL_MACRO;
  458. goto fail;
  459. }
  460. return true;
  461. fail:
  462. return false;
  463. }
  464. //------------------------------------------------------------------------------
  465. // open a cached directory entry.
  466. bool FatFile::openCachedEntry(FatFile* dirFile, uint16_t dirIndex,
  467. uint8_t oflag, uint8_t lfnOrd) {
  468. uint32_t firstCluster;
  469. memset(this, 0, sizeof(FatFile));
  470. // location of entry in cache
  471. m_vol = dirFile->m_vol;
  472. m_dirIndex = dirIndex;
  473. m_dirCluster = dirFile->m_firstCluster;
  474. dir_t* dir = &m_vol->cacheAddress()->dir[0XF & dirIndex];
  475. // Must be file or subdirectory.
  476. if (!DIR_IS_FILE_OR_SUBDIR(dir)) {
  477. DBG_FAIL_MACRO;
  478. goto fail;
  479. }
  480. m_attr = dir->attributes & FILE_ATTR_COPY;
  481. if (DIR_IS_FILE(dir)) {
  482. m_attr |= FILE_ATTR_FILE;
  483. }
  484. m_lfnOrd = lfnOrd;
  485. // Write, truncate, or at end is an error for a directory or read-only file.
  486. if (oflag & (O_WRITE | O_TRUNC | O_AT_END)) {
  487. if (isSubDir() || isReadOnly()) {
  488. DBG_FAIL_MACRO;
  489. goto fail;
  490. }
  491. }
  492. // save open flags for read/write
  493. m_flags = oflag & F_OFLAG;
  494. m_dirBlock = m_vol->cacheBlockNumber();
  495. // copy first cluster number for directory fields
  496. firstCluster = ((uint32_t)dir->firstClusterHigh << 16)
  497. | dir->firstClusterLow;
  498. if (oflag & O_TRUNC) {
  499. if (firstCluster && !m_vol->freeChain(firstCluster)) {
  500. DBG_FAIL_MACRO;
  501. goto fail;
  502. }
  503. // need to update directory entry
  504. m_flags |= F_FILE_DIR_DIRTY;
  505. } else {
  506. m_firstCluster = firstCluster;
  507. m_fileSize = dir->fileSize;
  508. }
  509. if ((oflag & O_AT_END) && !seekSet(m_fileSize)) {
  510. DBG_FAIL_MACRO;
  511. goto fail;
  512. }
  513. return true;
  514. fail:
  515. m_attr = FILE_ATTR_CLOSED;
  516. return false;
  517. }
  518. //------------------------------------------------------------------------------
  519. bool FatFile::openNext(FatFile* dirFile, uint8_t oflag) {
  520. uint8_t chksum = 0;
  521. ldir_t* ldir;
  522. uint8_t lfnOrd = 0;
  523. uint16_t index;
  524. // Check for not open and valid directory..
  525. if (isOpen() || !dirFile->isDir() || (dirFile->curPosition() & 0X1F)) {
  526. DBG_FAIL_MACRO;
  527. goto fail;
  528. }
  529. while (1) {
  530. // read entry into cache
  531. index = dirFile->curPosition()/32;
  532. dir_t* dir = dirFile->readDirCache();
  533. if (!dir) {
  534. if (dirFile->getError()) {
  535. DBG_FAIL_MACRO;
  536. }
  537. goto fail;
  538. }
  539. // done if last entry
  540. if (dir->name[0] == DIR_NAME_FREE) {
  541. goto fail;
  542. }
  543. // skip empty slot or '.' or '..'
  544. if (dir->name[0] == '.' || dir->name[0] == DIR_NAME_DELETED) {
  545. lfnOrd = 0;
  546. } else if (DIR_IS_FILE_OR_SUBDIR(dir)) {
  547. if (lfnOrd && chksum != lfnChecksum(dir->name)) {
  548. DBG_FAIL_MACRO;
  549. goto fail;
  550. }
  551. if (!openCachedEntry(dirFile, index, oflag, lfnOrd)) {
  552. DBG_FAIL_MACRO;
  553. goto fail;
  554. }
  555. return true;
  556. } else if (DIR_IS_LONG_NAME(dir)) {
  557. ldir = reinterpret_cast<ldir_t*>(dir);
  558. if (ldir->ord & LDIR_ORD_LAST_LONG_ENTRY) {
  559. lfnOrd = ldir->ord & 0X1F;
  560. chksum = ldir->chksum;
  561. }
  562. } else {
  563. lfnOrd = 0;
  564. }
  565. }
  566. fail:
  567. return false;
  568. }
  569. #ifndef DOXYGEN_SHOULD_SKIP_THIS
  570. //------------------------------------------------------------------------------
  571. /** Open a file's parent directory.
  572. *
  573. * \param[in] file Parent of this directory will be opened. Must not be root.
  574. *
  575. * \return The value true is returned for success and
  576. * the value false is returned for failure.
  577. */
  578. bool FatFile::openParent(FatFile* dirFile) {
  579. FatFile dotdot;
  580. uint32_t lbn;
  581. dir_t* dir;
  582. uint32_t ddc;
  583. cache_t* cb;
  584. if (isOpen() || !dirFile->isOpen()) {
  585. goto fail;
  586. }
  587. if (dirFile->m_dirCluster == 0) {
  588. return openRoot(dirFile->m_vol);
  589. }
  590. lbn = dirFile->m_vol->clusterFirstBlock(dirFile->m_dirCluster);
  591. cb = dirFile->m_vol->cacheFetchData(lbn, FatCache::CACHE_FOR_READ);
  592. if (!cb) {
  593. DBG_FAIL_MACRO;
  594. goto fail;
  595. }
  596. // Point to dir entery for ..
  597. dir = cb->dir + 1;
  598. ddc = dir->firstClusterLow | ((uint32_t)dir->firstClusterHigh << 16);
  599. if (ddc == 0) {
  600. if (!dotdot.openRoot(dirFile->m_vol)) {
  601. DBG_FAIL_MACRO;
  602. goto fail;
  603. }
  604. } else {
  605. memset(&dotdot, 0, sizeof(FatFile));
  606. dotdot.m_attr = FILE_ATTR_SUBDIR;
  607. dotdot.m_flags = O_READ;
  608. dotdot.m_vol = dirFile->m_vol;
  609. dotdot.m_firstCluster = ddc;
  610. }
  611. uint32_t di;
  612. do {
  613. di = dotdot.curPosition()/32;
  614. dir = dotdot.readDirCache();
  615. if (!dir) {
  616. DBG_FAIL_MACRO;
  617. goto fail;
  618. }
  619. ddc = dir->firstClusterLow | ((uint32_t)dir->firstClusterHigh << 16);
  620. } while (ddc != dirFile->m_dirCluster);
  621. return open(&dotdot, di, O_READ);
  622. fail:
  623. return false;
  624. }
  625. #endif // DOXYGEN_SHOULD_SKIP_THIS
  626. //------------------------------------------------------------------------------
  627. bool FatFile::openRoot(FatVolume* vol) {
  628. // error if file is already open
  629. if (isOpen()) {
  630. DBG_FAIL_MACRO;
  631. goto fail;
  632. }
  633. memset(this, 0, sizeof(FatFile));
  634. m_vol = vol;
  635. switch (vol->fatType()) {
  636. #if FAT12_SUPPORT
  637. case 12:
  638. #endif // FAT12_SUPPORT
  639. case 16:
  640. m_attr = FILE_ATTR_ROOT_FIXED;
  641. break;
  642. case 32:
  643. m_attr = FILE_ATTR_ROOT32;
  644. break;
  645. default:
  646. DBG_FAIL_MACRO;
  647. goto fail;
  648. }
  649. // read only
  650. m_flags = O_READ;
  651. return true;
  652. fail:
  653. return false;
  654. }
  655. //------------------------------------------------------------------------------
  656. int FatFile::peek() {
  657. FatPos_t pos;
  658. getpos(&pos);
  659. int c = read();
  660. if (c >= 0) {
  661. setpos(&pos);
  662. }
  663. return c;
  664. }
  665. //------------------------------------------------------------------------------
  666. int FatFile::read(void* buf, size_t nbyte) {
  667. int8_t fg;
  668. uint8_t blockOfCluster = 0;
  669. uint8_t* dst = reinterpret_cast<uint8_t*>(buf);
  670. uint16_t offset;
  671. size_t toRead;
  672. uint32_t block; // raw device block number
  673. cache_t* pc;
  674. // error if not open for read
  675. if (!isOpen() || !(m_flags & O_READ)) {
  676. DBG_FAIL_MACRO;
  677. goto fail;
  678. }
  679. if (isFile()) {
  680. uint32_t tmp32 = m_fileSize - m_curPosition;
  681. if (nbyte >= tmp32) {
  682. nbyte = tmp32;
  683. }
  684. } else if (isRootFixed()) {
  685. uint16_t tmp16 = 32*m_vol->m_rootDirEntryCount - (uint16_t)m_curPosition;
  686. if (nbyte > tmp16) {
  687. nbyte = tmp16;
  688. }
  689. }
  690. toRead = nbyte;
  691. while (toRead) {
  692. size_t n;
  693. offset = m_curPosition & 0X1FF; // offset in block
  694. if (isRootFixed()) {
  695. block = m_vol->rootDirStart() + (m_curPosition >> 9);
  696. } else {
  697. blockOfCluster = m_vol->blockOfCluster(m_curPosition);
  698. if (offset == 0 && blockOfCluster == 0) {
  699. // start of new cluster
  700. if (m_curPosition == 0) {
  701. // use first cluster in file
  702. m_curCluster = isRoot32() ? m_vol->rootDirStart() : m_firstCluster;
  703. } else {
  704. // get next cluster from FAT
  705. fg = m_vol->fatGet(m_curCluster, &m_curCluster);
  706. if (fg < 0) {
  707. DBG_FAIL_MACRO;
  708. goto fail;
  709. }
  710. if (fg == 0) {
  711. if (isDir()) {
  712. break;
  713. }
  714. DBG_FAIL_MACRO;
  715. goto fail;
  716. }
  717. }
  718. }
  719. block = m_vol->clusterFirstBlock(m_curCluster) + blockOfCluster;
  720. }
  721. if (offset != 0 || toRead < 512 || block == m_vol->cacheBlockNumber()) {
  722. // amount to be read from current block
  723. n = 512 - offset;
  724. if (n > toRead) {
  725. n = toRead;
  726. }
  727. // read block to cache and copy data to caller
  728. pc = m_vol->cacheFetchData(block, FatCache::CACHE_FOR_READ);
  729. if (!pc) {
  730. DBG_FAIL_MACRO;
  731. goto fail;
  732. }
  733. uint8_t* src = pc->data + offset;
  734. memcpy(dst, src, n);
  735. #if USE_MULTI_BLOCK_IO
  736. } else if (toRead >= 1024) {
  737. size_t nb = toRead >> 9;
  738. if (!isRootFixed()) {
  739. uint8_t mb = m_vol->blocksPerCluster() - blockOfCluster;
  740. if (mb < nb) {
  741. nb = mb;
  742. }
  743. }
  744. n = 512*nb;
  745. if (block <= m_vol->cacheBlockNumber()
  746. && block < (m_vol->cacheBlockNumber() + nb)) {
  747. // flush cache if a block is in the cache
  748. if (!m_vol->cacheSyncData()) {
  749. DBG_FAIL_MACRO;
  750. goto fail;
  751. }
  752. }
  753. if (!m_vol->readBlocks(block, dst, nb)) {
  754. DBG_FAIL_MACRO;
  755. goto fail;
  756. }
  757. #endif // USE_MULTI_BLOCK_IO
  758. } else {
  759. // read single block
  760. n = 512;
  761. if (!m_vol->readBlock(block, dst)) {
  762. DBG_FAIL_MACRO;
  763. goto fail;
  764. }
  765. }
  766. dst += n;
  767. m_curPosition += n;
  768. toRead -= n;
  769. }
  770. return nbyte - toRead;
  771. fail:
  772. m_error |= READ_ERROR;
  773. return -1;
  774. }
  775. //------------------------------------------------------------------------------
  776. int8_t FatFile::readDir(dir_t* dir) {
  777. int16_t n;
  778. // if not a directory file or miss-positioned return an error
  779. if (!isDir() || (0X1F & m_curPosition)) {
  780. return -1;
  781. }
  782. while (1) {
  783. n = read(dir, sizeof(dir_t));
  784. if (n != sizeof(dir_t)) {
  785. return n == 0 ? 0 : -1;
  786. }
  787. // last entry if DIR_NAME_FREE
  788. if (dir->name[0] == DIR_NAME_FREE) {
  789. return 0;
  790. }
  791. // skip empty entries and entry for . and ..
  792. if (dir->name[0] == DIR_NAME_DELETED || dir->name[0] == '.') {
  793. continue;
  794. }
  795. // return if normal file or subdirectory
  796. if (DIR_IS_FILE_OR_SUBDIR(dir)) {
  797. return n;
  798. }
  799. }
  800. }
  801. //------------------------------------------------------------------------------
  802. // Read next directory entry into the cache
  803. // Assumes file is correctly positioned
  804. dir_t* FatFile::readDirCache(bool skipReadOk) {
  805. // uint8_t b;
  806. uint8_t i = (m_curPosition >> 5) & 0XF;
  807. if (i == 0 || !skipReadOk) {
  808. int8_t n = read(&n, 1);
  809. if (n != 1) {
  810. if (n != 0) {
  811. DBG_FAIL_MACRO;
  812. }
  813. goto fail;
  814. }
  815. m_curPosition += 31;
  816. } else {
  817. m_curPosition += 32;
  818. }
  819. // return pointer to entry
  820. return m_vol->cacheAddress()->dir + i;
  821. fail:
  822. return 0;
  823. }
  824. //------------------------------------------------------------------------------
  825. bool FatFile::remove(FatFile* dirFile, const char* path) {
  826. FatFile file;
  827. if (!file.open(dirFile, path, O_WRITE)) {
  828. DBG_FAIL_MACRO;
  829. goto fail;
  830. }
  831. return file.remove();
  832. fail:
  833. return false;
  834. }
  835. //------------------------------------------------------------------------------
  836. bool FatFile::rename(FatFile* dirFile, const char* newPath) {
  837. dir_t entry;
  838. uint32_t dirCluster = 0;
  839. FatFile file;
  840. FatFile oldFile;
  841. cache_t* pc;
  842. dir_t* dir;
  843. // Must be an open file or subdirectory.
  844. if (!(isFile() || isSubDir())) {
  845. DBG_FAIL_MACRO;
  846. goto fail;
  847. }
  848. // Can't rename LFN in 8.3 mode.
  849. if (!USE_LONG_FILE_NAMES && isLFN()) {
  850. DBG_FAIL_MACRO;
  851. goto fail;
  852. }
  853. // Can't move file to new volume.
  854. if (m_vol != dirFile->m_vol) {
  855. DBG_FAIL_MACRO;
  856. goto fail;
  857. }
  858. // sync() and cache directory entry
  859. sync();
  860. oldFile = *this;
  861. dir = cacheDirEntry(FatCache::CACHE_FOR_READ);
  862. if (!dir) {
  863. DBG_FAIL_MACRO;
  864. goto fail;
  865. }
  866. // save directory entry
  867. memcpy(&entry, dir, sizeof(entry));
  868. // make directory entry for new path
  869. if (isFile()) {
  870. if (!file.open(dirFile, newPath, O_CREAT | O_EXCL | O_WRITE)) {
  871. DBG_FAIL_MACRO;
  872. goto fail;
  873. }
  874. } else {
  875. // don't create missing path prefix components
  876. if (!file.mkdir(dirFile, newPath, false)) {
  877. DBG_FAIL_MACRO;
  878. goto fail;
  879. }
  880. // save cluster containing new dot dot
  881. dirCluster = file.m_firstCluster;
  882. }
  883. // change to new directory entry
  884. m_dirBlock = file.m_dirBlock;
  885. m_dirIndex = file.m_dirIndex;
  886. m_lfnOrd = file.m_lfnOrd;
  887. m_dirCluster = file.m_dirCluster;
  888. // mark closed to avoid possible destructor close call
  889. file.m_attr = FILE_ATTR_CLOSED;
  890. // cache new directory entry
  891. dir = cacheDirEntry(FatCache::CACHE_FOR_WRITE);
  892. if (!dir) {
  893. DBG_FAIL_MACRO;
  894. goto fail;
  895. }
  896. // copy all but name and name flags to new directory entry
  897. memcpy(&dir->creationTimeTenths, &entry.creationTimeTenths,
  898. sizeof(entry) - sizeof(dir->name) - 2);
  899. dir->attributes = entry.attributes;
  900. // update dot dot if directory
  901. if (dirCluster) {
  902. // get new dot dot
  903. uint32_t block = m_vol->clusterFirstBlock(dirCluster);
  904. pc = m_vol->cacheFetchData(block, FatCache::CACHE_FOR_READ);
  905. if (!pc) {
  906. DBG_FAIL_MACRO;
  907. goto fail;
  908. }
  909. memcpy(&entry, &pc->dir[1], sizeof(entry));
  910. // free unused cluster
  911. if (!m_vol->freeChain(dirCluster)) {
  912. DBG_FAIL_MACRO;
  913. goto fail;
  914. }
  915. // store new dot dot
  916. block = m_vol->clusterFirstBlock(m_firstCluster);
  917. pc = m_vol->cacheFetchData(block, FatCache::CACHE_FOR_WRITE);
  918. if (!pc) {
  919. DBG_FAIL_MACRO;
  920. goto fail;
  921. }
  922. memcpy(&pc->dir[1], &entry, sizeof(entry));
  923. }
  924. // Remove old directory entry;
  925. oldFile.m_firstCluster = 0;
  926. oldFile.m_flags = O_WRITE;
  927. oldFile.m_attr = FILE_ATTR_FILE;
  928. if (!oldFile.remove()) {
  929. DBG_FAIL_MACRO;
  930. goto fail;
  931. }
  932. return m_vol->cacheSync();
  933. fail:
  934. return false;
  935. }
  936. //------------------------------------------------------------------------------
  937. bool FatFile::rmdir() {
  938. // must be open subdirectory
  939. if (!isSubDir() || (!USE_LONG_FILE_NAMES && isLFN())) {
  940. DBG_FAIL_MACRO;
  941. goto fail;
  942. }
  943. rewind();
  944. // make sure directory is empty
  945. while (1) {
  946. dir_t* dir = readDirCache(true);
  947. if (!dir) {
  948. // EOF if no error.
  949. if (!getError()) {
  950. break;
  951. }
  952. DBG_FAIL_MACRO;
  953. goto fail;
  954. }
  955. // done if past last used entry
  956. if (dir->name[0] == DIR_NAME_FREE) {
  957. break;
  958. }
  959. // skip empty slot, '.' or '..'
  960. if (dir->name[0] == DIR_NAME_DELETED || dir->name[0] == '.') {
  961. continue;
  962. }
  963. // error not empty
  964. if (DIR_IS_FILE_OR_SUBDIR(dir)) {
  965. DBG_FAIL_MACRO;
  966. goto fail;
  967. }
  968. }
  969. // convert empty directory to normal file for remove
  970. m_attr = FILE_ATTR_FILE;
  971. m_flags |= O_WRITE;
  972. return remove();
  973. fail:
  974. return false;
  975. }
  976. //------------------------------------------------------------------------------
  977. bool FatFile::rmRfStar() {
  978. uint16_t index;
  979. FatFile f;
  980. if (!isDir()) {
  981. DBG_FAIL_MACRO;
  982. goto fail;
  983. }
  984. rewind();
  985. while (1) {
  986. // remember position
  987. index = m_curPosition/32;
  988. dir_t* dir = readDirCache();
  989. if (!dir) {
  990. // At EOF if no error.
  991. if (!getError()) {
  992. break;
  993. }
  994. DBG_FAIL_MACRO;
  995. goto fail;
  996. }
  997. // done if past last entry
  998. if (dir->name[0] == DIR_NAME_FREE) {
  999. break;
  1000. }
  1001. // skip empty slot or '.' or '..'
  1002. if (dir->name[0] == DIR_NAME_DELETED || dir->name[0] == '.') {
  1003. continue;
  1004. }
  1005. // skip if part of long file name or volume label in root
  1006. if (!DIR_IS_FILE_OR_SUBDIR(dir)) {
  1007. continue;
  1008. }
  1009. if (!f.open(this, index, O_READ)) {
  1010. DBG_FAIL_MACRO;
  1011. goto fail;
  1012. }
  1013. if (f.isSubDir()) {
  1014. // recursively delete
  1015. if (!f.rmRfStar()) {
  1016. DBG_FAIL_MACRO;
  1017. goto fail;
  1018. }
  1019. } else {
  1020. // ignore read-only
  1021. f.m_flags |= O_WRITE;
  1022. if (!f.remove()) {
  1023. DBG_FAIL_MACRO;
  1024. goto fail;
  1025. }
  1026. }
  1027. // position to next entry if required
  1028. if (m_curPosition != (32UL*(index + 1))) {
  1029. if (!seekSet(32UL*(index + 1))) {
  1030. DBG_FAIL_MACRO;
  1031. goto fail;
  1032. }
  1033. }
  1034. }
  1035. // don't try to delete root
  1036. if (!isRoot()) {
  1037. if (!rmdir()) {
  1038. DBG_FAIL_MACRO;
  1039. goto fail;
  1040. }
  1041. }
  1042. return true;
  1043. fail:
  1044. return false;
  1045. }
  1046. //------------------------------------------------------------------------------
  1047. bool FatFile::seekSet(uint32_t pos) {
  1048. uint32_t nCur;
  1049. uint32_t nNew;
  1050. uint32_t tmp = m_curCluster;
  1051. // error if file not open
  1052. if (!isOpen()) {
  1053. DBG_FAIL_MACRO;
  1054. goto fail;
  1055. }
  1056. // Optimize O_APPEND writes.
  1057. if (pos == m_curPosition) {
  1058. return true;
  1059. }
  1060. if (pos == 0) {
  1061. // set position to start of file
  1062. m_curCluster = 0;
  1063. goto done;
  1064. }
  1065. if (isFile()) {
  1066. if (pos > m_fileSize) {
  1067. DBG_FAIL_MACRO;
  1068. goto fail;
  1069. }
  1070. } else if (isRootFixed()) {
  1071. if (pos <= 32*m_vol->rootDirEntryCount()) {
  1072. goto done;
  1073. }
  1074. DBG_FAIL_MACRO;
  1075. goto fail;
  1076. }
  1077. // calculate cluster index for cur and new position
  1078. nCur = (m_curPosition - 1) >> (m_vol->clusterSizeShift() + 9);
  1079. nNew = (pos - 1) >> (m_vol->clusterSizeShift() + 9);
  1080. if (nNew < nCur || m_curPosition == 0) {
  1081. // must follow chain from first cluster
  1082. m_curCluster = isRoot32() ? m_vol->rootDirStart() : m_firstCluster;
  1083. } else {
  1084. // advance from curPosition
  1085. nNew -= nCur;
  1086. }
  1087. while (nNew--) {
  1088. if (m_vol->fatGet(m_curCluster, &m_curCluster) <= 0) {
  1089. DBG_FAIL_MACRO;
  1090. goto fail;
  1091. }
  1092. }
  1093. done:
  1094. m_curPosition = pos;
  1095. return true;
  1096. fail:
  1097. m_curCluster = tmp;
  1098. return false;
  1099. }
  1100. //------------------------------------------------------------------------------
  1101. void FatFile::setpos(FatPos_t* pos) {
  1102. m_curPosition = pos->position;
  1103. m_curCluster = pos->cluster;
  1104. }
  1105. //------------------------------------------------------------------------------
  1106. bool FatFile::sync() {
  1107. if (!isOpen()) {
  1108. return true;
  1109. }
  1110. if (m_flags & F_FILE_DIR_DIRTY) {
  1111. dir_t* dir = cacheDirEntry(FatCache::CACHE_FOR_WRITE);
  1112. // check for deleted by another open file object
  1113. if (!dir || dir->name[0] == DIR_NAME_DELETED) {
  1114. DBG_FAIL_MACRO;
  1115. goto fail;
  1116. }
  1117. // do not set filesize for dir files
  1118. if (isFile()) {
  1119. dir->fileSize = m_fileSize;
  1120. }
  1121. // update first cluster fields
  1122. dir->firstClusterLow = m_firstCluster & 0XFFFF;
  1123. dir->firstClusterHigh = m_firstCluster >> 16;
  1124. // set modify time if user supplied a callback date/time function
  1125. if (m_dateTime) {
  1126. m_dateTime(&dir->lastWriteDate, &dir->lastWriteTime);
  1127. dir->lastAccessDate = dir->lastWriteDate;
  1128. }
  1129. // clear directory dirty
  1130. m_flags &= ~F_FILE_DIR_DIRTY;
  1131. }
  1132. if (m_vol->cacheSync()) {
  1133. return true;
  1134. }
  1135. DBG_FAIL_MACRO;
  1136. fail:
  1137. m_error |= WRITE_ERROR;
  1138. return false;
  1139. }
  1140. //------------------------------------------------------------------------------
  1141. bool FatFile::timestamp(FatFile* file) {
  1142. dir_t* dir;
  1143. dir_t srcDir;
  1144. // most be files get timestamps
  1145. if (!isFile() || !file->isFile() || !file->dirEntry(&srcDir)) {
  1146. DBG_FAIL_MACRO;
  1147. goto fail;
  1148. }
  1149. // update directory fields
  1150. if (!sync()) {
  1151. DBG_FAIL_MACRO;
  1152. goto fail;
  1153. }
  1154. dir = cacheDirEntry(FatCache::CACHE_FOR_WRITE);
  1155. if (!dir) {
  1156. DBG_FAIL_MACRO;
  1157. goto fail;
  1158. }
  1159. // copy timestamps
  1160. dir->lastAccessDate = srcDir.lastAccessDate;
  1161. dir->creationDate = srcDir.creationDate;
  1162. dir->creationTime = srcDir.creationTime;
  1163. dir->creationTimeTenths = srcDir.creationTimeTenths;
  1164. dir->lastWriteDate = srcDir.lastWriteDate;
  1165. dir->lastWriteTime = srcDir.lastWriteTime;
  1166. // write back entry
  1167. return m_vol->cacheSync();
  1168. fail:
  1169. return false;
  1170. }
  1171. //------------------------------------------------------------------------------
  1172. bool FatFile::timestamp(uint8_t flags, uint16_t year, uint8_t month,
  1173. uint8_t day, uint8_t hour, uint8_t minute, uint8_t second) {
  1174. uint16_t dirDate;
  1175. uint16_t dirTime;
  1176. dir_t* dir;
  1177. if (!isFile()
  1178. || year < 1980
  1179. || year > 2107
  1180. || month < 1
  1181. || month > 12
  1182. || day < 1
  1183. || day > 31
  1184. || hour > 23
  1185. || minute > 59
  1186. || second > 59) {
  1187. DBG_FAIL_MACRO;
  1188. goto fail;
  1189. }
  1190. // update directory entry
  1191. if (!sync()) {
  1192. DBG_FAIL_MACRO;
  1193. goto fail;
  1194. }
  1195. dir = cacheDirEntry(FatCache::CACHE_FOR_WRITE);
  1196. if (!dir) {
  1197. DBG_FAIL_MACRO;
  1198. goto fail;
  1199. }
  1200. dirDate = FAT_DATE(year, month, day);
  1201. dirTime = FAT_TIME(hour, minute, second);
  1202. if (flags & T_ACCESS) {
  1203. dir->lastAccessDate = dirDate;
  1204. }
  1205. if (flags & T_CREATE) {
  1206. dir->creationDate = dirDate;
  1207. dir->creationTime = dirTime;
  1208. // seems to be units of 1/100 second not 1/10 as Microsoft states
  1209. dir->creationTimeTenths = second & 1 ? 100 : 0;
  1210. }
  1211. if (flags & T_WRITE) {
  1212. dir->lastWriteDate = dirDate;
  1213. dir->lastWriteTime = dirTime;
  1214. }
  1215. return m_vol->cacheSync();
  1216. fail:
  1217. return false;
  1218. }
  1219. //------------------------------------------------------------------------------
  1220. bool FatFile::truncate(uint32_t length) {
  1221. uint32_t newPos;
  1222. // error if not a normal file or read-only
  1223. if (!isFile() || !(m_flags & O_WRITE)) {
  1224. DBG_FAIL_MACRO;
  1225. goto fail;
  1226. }
  1227. // error if length is greater than current size
  1228. if (length > m_fileSize) {
  1229. DBG_FAIL_MACRO;
  1230. goto fail;
  1231. }
  1232. // fileSize and length are zero - nothing to do
  1233. if (m_fileSize == 0) {
  1234. return true;
  1235. }
  1236. // remember position for seek after truncation
  1237. newPos = m_curPosition > length ? length : m_curPosition;
  1238. // position to last cluster in truncated file
  1239. if (!seekSet(length)) {
  1240. DBG_FAIL_MACRO;
  1241. goto fail;
  1242. }
  1243. if (length == 0) {
  1244. // free all clusters
  1245. if (!m_vol->freeChain(m_firstCluster)) {
  1246. DBG_FAIL_MACRO;
  1247. goto fail;
  1248. }
  1249. m_firstCluster = 0;
  1250. } else {
  1251. uint32_t toFree;
  1252. int8_t fg = m_vol->fatGet(m_curCluster, &toFree);
  1253. if (fg < 0) {
  1254. DBG_FAIL_MACRO;
  1255. goto fail;
  1256. }
  1257. if (fg) {
  1258. // free extra clusters
  1259. if (!m_vol->freeChain(toFree)) {
  1260. DBG_FAIL_MACRO;
  1261. goto fail;
  1262. }
  1263. // current cluster is end of chain
  1264. if (!m_vol->fatPutEOC(m_curCluster)) {
  1265. DBG_FAIL_MACRO;
  1266. goto fail;
  1267. }
  1268. }
  1269. }
  1270. m_fileSize = length;
  1271. // need to update directory entry
  1272. m_flags |= F_FILE_DIR_DIRTY;
  1273. if (!sync()) {
  1274. DBG_FAIL_MACRO;
  1275. goto fail;
  1276. }
  1277. // set file to correct position
  1278. return seekSet(newPos);
  1279. fail:
  1280. return false;
  1281. }
  1282. //------------------------------------------------------------------------------
  1283. int FatFile::write(const void* buf, size_t nbyte) {
  1284. // convert void* to uint8_t* - must be before goto statements
  1285. const uint8_t* src = reinterpret_cast<const uint8_t*>(buf);
  1286. cache_t* pc;
  1287. uint8_t cacheOption;
  1288. // number of bytes left to write - must be before goto statements
  1289. size_t nToWrite = nbyte;
  1290. size_t n;
  1291. // error if not a normal file or is read-only
  1292. if (!isFile() || !(m_flags & O_WRITE)) {
  1293. DBG_FAIL_MACRO;
  1294. goto fail;
  1295. }
  1296. // seek to end of file if append flag
  1297. if ((m_flags & O_APPEND)) {
  1298. if (!seekSet(m_fileSize)) {
  1299. DBG_FAIL_MACRO;
  1300. goto fail;
  1301. }
  1302. }
  1303. // Don't exceed max fileSize.
  1304. if (nbyte > (0XFFFFFFFF - m_curPosition)) {
  1305. DBG_FAIL_MACRO;
  1306. goto fail;
  1307. }
  1308. while (nToWrite) {
  1309. uint8_t blockOfCluster = m_vol->blockOfCluster(m_curPosition);
  1310. uint16_t blockOffset = m_curPosition & 0X1FF;
  1311. if (blockOfCluster == 0 && blockOffset == 0) {
  1312. // start of new cluster
  1313. if (m_curCluster != 0) {
  1314. int8_t fg = m_vol->fatGet(m_curCluster, &m_curCluster);
  1315. if (fg < 0) {
  1316. DBG_FAIL_MACRO;
  1317. goto fail;
  1318. }
  1319. if (fg == 0) {
  1320. // add cluster if at end of chain
  1321. if (!addCluster()) {
  1322. DBG_FAIL_MACRO;
  1323. goto fail;
  1324. }
  1325. }
  1326. } else {
  1327. if (m_firstCluster == 0) {
  1328. // allocate first cluster of file
  1329. if (!addCluster()) {
  1330. DBG_FAIL_MACRO;
  1331. goto fail;
  1332. }
  1333. m_firstCluster = m_curCluster;
  1334. } else {
  1335. m_curCluster = m_firstCluster;
  1336. }
  1337. }
  1338. }
  1339. // block for data write
  1340. uint32_t block = m_vol->clusterFirstBlock(m_curCluster) + blockOfCluster;
  1341. if (blockOffset != 0 || nToWrite < 512) {
  1342. // partial block - must use cache
  1343. // max space in block
  1344. n = 512 - blockOffset;
  1345. // lesser of space and amount to write
  1346. if (n > nToWrite) {
  1347. n = nToWrite;
  1348. }
  1349. if (blockOffset == 0 && m_curPosition >= m_fileSize) {
  1350. // start of new block don't need to read into cache
  1351. cacheOption = FatCache::CACHE_RESERVE_FOR_WRITE;
  1352. } else {
  1353. // rewrite part of block
  1354. cacheOption = FatCache::CACHE_FOR_WRITE;
  1355. }
  1356. pc = m_vol->cacheFetchData(block, cacheOption);
  1357. if (!pc) {
  1358. DBG_FAIL_MACRO;
  1359. goto fail;
  1360. }
  1361. uint8_t* dst = pc->data + blockOffset;
  1362. memcpy(dst, src, n);
  1363. if (512 == (n + blockOffset)) {
  1364. // Force write if block is full - improves large writes.
  1365. if (!m_vol->cacheSyncData()) {
  1366. DBG_FAIL_MACRO;
  1367. goto fail;
  1368. }
  1369. }
  1370. #if USE_MULTI_BLOCK_IO
  1371. } else if (nToWrite >= 1024) {
  1372. // use multiple block write command
  1373. uint8_t maxBlocks = m_vol->blocksPerCluster() - blockOfCluster;
  1374. size_t nBlock = nToWrite >> 9;
  1375. if (nBlock > maxBlocks) {
  1376. nBlock = maxBlocks;
  1377. }
  1378. n = 512*nBlock;
  1379. if (block <= m_vol->cacheBlockNumber()
  1380. && block < (m_vol->cacheBlockNumber() + nBlock)) {
  1381. // invalidate cache if block is in cache
  1382. m_vol->cacheInvalidate();
  1383. }
  1384. if (!m_vol->writeBlocks(block, src, nBlock)) {
  1385. DBG_FAIL_MACRO;
  1386. goto fail;
  1387. }
  1388. #endif // USE_MULTI_BLOCK_IO
  1389. } else {
  1390. // use single block write command
  1391. n = 512;
  1392. if (m_vol->cacheBlockNumber() == block) {
  1393. m_vol->cacheInvalidate();
  1394. }
  1395. if (!m_vol->writeBlock(block, src)) {
  1396. DBG_FAIL_MACRO;
  1397. goto fail;
  1398. }
  1399. }
  1400. m_curPosition += n;
  1401. src += n;
  1402. nToWrite -= n;
  1403. }
  1404. if (m_curPosition > m_fileSize) {
  1405. // update fileSize and insure sync will update dir entry
  1406. m_fileSize = m_curPosition;
  1407. m_flags |= F_FILE_DIR_DIRTY;
  1408. } else if (m_dateTime) {
  1409. // insure sync will update modified date and time
  1410. m_flags |= F_FILE_DIR_DIRTY;
  1411. }
  1412. if (m_flags & O_SYNC) {
  1413. if (!sync()) {
  1414. DBG_FAIL_MACRO;
  1415. goto fail;
  1416. }
  1417. }
  1418. return nbyte;
  1419. fail:
  1420. // return for write error
  1421. m_error |= WRITE_ERROR;
  1422. return -1;
  1423. }