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 52KB

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