My Marlin configs for Fabrikator Mini and CTC i3 Pro B
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

SdBaseFile.cpp 50KB

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