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.

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