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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729
  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 ? -1 : 0;
  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) {
  954. const uint8_t seq = VFAT->sequenceNumber & 0x1F;
  955. if (WITHIN(seq, 1, MAX_VFAT_ENTRIES)) {
  956. // TODO: Store the filename checksum to verify if a long-filename-unaware system modified the file table.
  957. n = (seq - 1) * (FILENAME_LENGTH);
  958. for (uint8_t i = 0; i < FILENAME_LENGTH; i++)
  959. longFilename[n + i] = (i < 5) ? VFAT->name1[i] : (i < 11) ? VFAT->name2[i - 5] : VFAT->name3[i - 11];
  960. // If this VFAT entry is the last one, add a NUL terminator at the end of the string
  961. if (VFAT->sequenceNumber & 0x40) longFilename[n + FILENAME_LENGTH] = '\0';
  962. }
  963. }
  964. }
  965. // Return if normal file or subdirectory
  966. if (DIR_IS_FILE_OR_SUBDIR(dir)) return n;
  967. }
  968. }
  969. // Read next directory entry into the cache
  970. // Assumes file is correctly positioned
  971. dir_t* SdBaseFile::readDirCache() {
  972. uint8_t i;
  973. // error if not directory
  974. if (!isDir()) return 0;
  975. // index of entry in cache
  976. i = (curPosition_ >> 5) & 0XF;
  977. // use read to locate and cache block
  978. if (read() < 0) return 0;
  979. // advance to next entry
  980. curPosition_ += 31;
  981. // return pointer to entry
  982. return vol_->cache()->dir + i;
  983. }
  984. /**
  985. * Remove a file.
  986. *
  987. * The directory entry and all data for the file are deleted.
  988. *
  989. * \note This function should not be used to delete the 8.3 version of a
  990. * file that has a long name. For example if a file has the long name
  991. * "New Text Document.txt" you should not delete the 8.3 name "NEWTEX~1.TXT".
  992. *
  993. * \return true for success, false for failure.
  994. * Reasons for failure include the file read-only, is a directory,
  995. * or an I/O error occurred.
  996. */
  997. bool SdBaseFile::remove() {
  998. dir_t* d;
  999. // free any clusters - will fail if read-only or directory
  1000. if (!truncate(0)) return false;
  1001. // cache directory entry
  1002. d = cacheDirEntry(SdVolume::CACHE_FOR_WRITE);
  1003. if (!d) return false;
  1004. // mark entry deleted
  1005. d->name[0] = DIR_NAME_DELETED;
  1006. // set this file closed
  1007. type_ = FAT_FILE_TYPE_CLOSED;
  1008. // write entry to SD
  1009. return vol_->cacheFlush();
  1010. return true;
  1011. }
  1012. /**
  1013. * Remove a file.
  1014. *
  1015. * The directory entry and all data for the file are deleted.
  1016. *
  1017. * \param[in] dirFile The directory that contains the file.
  1018. * \param[in] path Path for the file to be removed.
  1019. *
  1020. * \note This function should not be used to delete the 8.3 version of a
  1021. * file that has a long name. For example if a file has the long name
  1022. * "New Text Document.txt" you should not delete the 8.3 name "NEWTEX~1.TXT".
  1023. *
  1024. * \return true for success, false for failure.
  1025. * Reasons for failure include the file is a directory, is read only,
  1026. * \a dirFile is not a directory, \a path is not found
  1027. * or an I/O error occurred.
  1028. */
  1029. bool SdBaseFile::remove(SdBaseFile* dirFile, const char* path) {
  1030. SdBaseFile file;
  1031. return file.open(dirFile, path, O_WRITE) ? file.remove() : false;
  1032. }
  1033. /**
  1034. * Rename a file or subdirectory.
  1035. *
  1036. * \param[in] dirFile Directory for the new path.
  1037. * \param[in] newPath New path name for the file/directory.
  1038. *
  1039. * \return true for success, false for failure.
  1040. * Reasons for failure include \a dirFile is not open or is not a directory
  1041. * file, newPath is invalid or already exists, or an I/O error occurs.
  1042. */
  1043. bool SdBaseFile::rename(SdBaseFile* dirFile, const char* newPath) {
  1044. dir_t entry;
  1045. uint32_t dirCluster = 0;
  1046. SdBaseFile file;
  1047. dir_t* d;
  1048. // must be an open file or subdirectory
  1049. if (!(isFile() || isSubDir())) return false;
  1050. // can't move file
  1051. if (vol_ != dirFile->vol_) return false;
  1052. // sync() and cache directory entry
  1053. sync();
  1054. d = cacheDirEntry(SdVolume::CACHE_FOR_WRITE);
  1055. if (!d) return false;
  1056. // save directory entry
  1057. memcpy(&entry, d, sizeof(entry));
  1058. // mark entry deleted
  1059. d->name[0] = DIR_NAME_DELETED;
  1060. // make directory entry for new path
  1061. if (isFile()) {
  1062. if (!file.open(dirFile, newPath, O_CREAT | O_EXCL | O_WRITE)) {
  1063. goto restore;
  1064. }
  1065. }
  1066. else {
  1067. // don't create missing path prefix components
  1068. if (!file.mkdir(dirFile, newPath, false)) {
  1069. goto restore;
  1070. }
  1071. // save cluster containing new dot dot
  1072. dirCluster = file.firstCluster_;
  1073. }
  1074. // change to new directory entry
  1075. dirBlock_ = file.dirBlock_;
  1076. dirIndex_ = file.dirIndex_;
  1077. // mark closed to avoid possible destructor close call
  1078. file.type_ = FAT_FILE_TYPE_CLOSED;
  1079. // cache new directory entry
  1080. d = cacheDirEntry(SdVolume::CACHE_FOR_WRITE);
  1081. if (!d) return false;
  1082. // copy all but name field to new directory entry
  1083. memcpy(&d->attributes, &entry.attributes, sizeof(entry) - sizeof(d->name));
  1084. // update dot dot if directory
  1085. if (dirCluster) {
  1086. // get new dot dot
  1087. uint32_t block = vol_->clusterStartBlock(dirCluster);
  1088. if (!vol_->cacheRawBlock(block, SdVolume::CACHE_FOR_READ)) return false;
  1089. memcpy(&entry, &vol_->cache()->dir[1], sizeof(entry));
  1090. // free unused cluster
  1091. if (!vol_->freeChain(dirCluster)) return false;
  1092. // store new dot dot
  1093. block = vol_->clusterStartBlock(firstCluster_);
  1094. if (!vol_->cacheRawBlock(block, SdVolume::CACHE_FOR_WRITE)) return false;
  1095. memcpy(&vol_->cache()->dir[1], &entry, sizeof(entry));
  1096. }
  1097. return vol_->cacheFlush();
  1098. restore:
  1099. if ((d = cacheDirEntry(SdVolume::CACHE_FOR_WRITE))) {
  1100. // restore entry
  1101. d->name[0] = entry.name[0];
  1102. vol_->cacheFlush();
  1103. }
  1104. return false;
  1105. }
  1106. /**
  1107. * Remove a directory file.
  1108. *
  1109. * The directory file will be removed only if it is empty and is not the
  1110. * root directory. rmdir() follows DOS and Windows and ignores the
  1111. * read-only attribute for the directory.
  1112. *
  1113. * \note This function should not be used to delete the 8.3 version of a
  1114. * directory that has a long name. For example if a directory has the
  1115. * long name "New folder" you should not delete the 8.3 name "NEWFOL~1".
  1116. *
  1117. * \return true for success, false for failure.
  1118. * Reasons for failure include the file is not a directory, is the root
  1119. * directory, is not empty, or an I/O error occurred.
  1120. */
  1121. bool SdBaseFile::rmdir() {
  1122. // must be open subdirectory
  1123. if (!isSubDir()) return false;
  1124. rewind();
  1125. // make sure directory is empty
  1126. while (curPosition_ < fileSize_) {
  1127. dir_t* p = readDirCache();
  1128. if (!p) return false;
  1129. // done if past last used entry
  1130. if (p->name[0] == DIR_NAME_FREE) break;
  1131. // skip empty slot, '.' or '..'
  1132. if (p->name[0] == DIR_NAME_DELETED || p->name[0] == '.') continue;
  1133. // error not empty
  1134. if (DIR_IS_FILE_OR_SUBDIR(p)) return false;
  1135. }
  1136. // convert empty directory to normal file for remove
  1137. type_ = FAT_FILE_TYPE_NORMAL;
  1138. flags_ |= O_WRITE;
  1139. return remove();
  1140. }
  1141. /**
  1142. * Recursively delete a directory and all contained files.
  1143. *
  1144. * This is like the Unix/Linux 'rm -rf *' if called with the root directory
  1145. * hence the name.
  1146. *
  1147. * Warning - This will remove all contents of the directory including
  1148. * subdirectories. The directory will then be removed if it is not root.
  1149. * The read-only attribute for files will be ignored.
  1150. *
  1151. * \note This function should not be used to delete the 8.3 version of
  1152. * a directory that has a long name. See remove() and rmdir().
  1153. *
  1154. * \return true for success, false for failure.
  1155. */
  1156. bool SdBaseFile::rmRfStar() {
  1157. uint32_t index;
  1158. SdBaseFile f;
  1159. rewind();
  1160. while (curPosition_ < fileSize_) {
  1161. // remember position
  1162. index = curPosition_ / 32;
  1163. dir_t* p = readDirCache();
  1164. if (!p) return false;
  1165. // done if past last entry
  1166. if (p->name[0] == DIR_NAME_FREE) break;
  1167. // skip empty slot or '.' or '..'
  1168. if (p->name[0] == DIR_NAME_DELETED || p->name[0] == '.') continue;
  1169. // skip if part of long file name or volume label in root
  1170. if (!DIR_IS_FILE_OR_SUBDIR(p)) continue;
  1171. if (!f.open(this, index, O_READ)) return false;
  1172. if (f.isSubDir()) {
  1173. // recursively delete
  1174. if (!f.rmRfStar()) return false;
  1175. }
  1176. else {
  1177. // ignore read-only
  1178. f.flags_ |= O_WRITE;
  1179. if (!f.remove()) return false;
  1180. }
  1181. // position to next entry if required
  1182. if (curPosition_ != (32 * (index + 1))) {
  1183. if (!seekSet(32 * (index + 1))) return false;
  1184. }
  1185. }
  1186. // don't try to delete root
  1187. if (!isRoot()) {
  1188. if (!rmdir()) return false;
  1189. }
  1190. return true;
  1191. }
  1192. /**
  1193. * Create a file object and open it in the current working directory.
  1194. *
  1195. * \param[in] path A path with a valid 8.3 DOS name for a file to be opened.
  1196. *
  1197. * \param[in] oflag Values for \a oflag are constructed by a bitwise-inclusive
  1198. * OR of open flags. see SdBaseFile::open(SdBaseFile*, const char*, uint8_t).
  1199. */
  1200. SdBaseFile::SdBaseFile(const char* path, uint8_t oflag) {
  1201. type_ = FAT_FILE_TYPE_CLOSED;
  1202. writeError = false;
  1203. open(path, oflag);
  1204. }
  1205. /**
  1206. * Sets a file's position.
  1207. *
  1208. * \param[in] pos The new position in bytes from the beginning of the file.
  1209. *
  1210. * \return true for success, false for failure.
  1211. */
  1212. bool SdBaseFile::seekSet(const uint32_t pos) {
  1213. uint32_t nCur, nNew;
  1214. // error if file not open or seek past end of file
  1215. if (!isOpen() || pos > fileSize_) return false;
  1216. if (type_ == FAT_FILE_TYPE_ROOT_FIXED) {
  1217. curPosition_ = pos;
  1218. return true;
  1219. }
  1220. if (pos == 0) {
  1221. curCluster_ = curPosition_ = 0; // set position to start of file
  1222. return true;
  1223. }
  1224. // calculate cluster index for cur and new position
  1225. nCur = (curPosition_ - 1) >> (vol_->clusterSizeShift_ + 9);
  1226. nNew = (pos - 1) >> (vol_->clusterSizeShift_ + 9);
  1227. if (nNew < nCur || curPosition_ == 0)
  1228. curCluster_ = firstCluster_; // must follow chain from first cluster
  1229. else
  1230. nNew -= nCur; // advance from curPosition
  1231. while (nNew--)
  1232. if (!vol_->fatGet(curCluster_, &curCluster_)) return false;
  1233. curPosition_ = pos;
  1234. return true;
  1235. }
  1236. void SdBaseFile::setpos(filepos_t* pos) {
  1237. curPosition_ = pos->position;
  1238. curCluster_ = pos->cluster;
  1239. }
  1240. /**
  1241. * The sync() call causes all modified data and directory fields
  1242. * to be written to the storage device.
  1243. *
  1244. * \return true for success, false for failure.
  1245. * Reasons for failure include a call to sync() before a file has been
  1246. * opened or an I/O error.
  1247. */
  1248. bool SdBaseFile::sync() {
  1249. // only allow open files and directories
  1250. if (!isOpen()) goto FAIL;
  1251. if (flags_ & F_FILE_DIR_DIRTY) {
  1252. dir_t* d = cacheDirEntry(SdVolume::CACHE_FOR_WRITE);
  1253. // check for deleted by another open file object
  1254. if (!d || d->name[0] == DIR_NAME_DELETED) goto FAIL;
  1255. // do not set filesize for dir files
  1256. if (!isDir()) d->fileSize = fileSize_;
  1257. // update first cluster fields
  1258. d->firstClusterLow = firstCluster_ & 0xFFFF;
  1259. d->firstClusterHigh = firstCluster_ >> 16;
  1260. // set modify time if user supplied a callback date/time function
  1261. if (dateTime_) {
  1262. dateTime_(&d->lastWriteDate, &d->lastWriteTime);
  1263. d->lastAccessDate = d->lastWriteDate;
  1264. }
  1265. // clear directory dirty
  1266. flags_ &= ~F_FILE_DIR_DIRTY;
  1267. }
  1268. return vol_->cacheFlush();
  1269. FAIL:
  1270. writeError = true;
  1271. return false;
  1272. }
  1273. /**
  1274. * Copy a file's timestamps
  1275. *
  1276. * \param[in] file File to copy timestamps from.
  1277. *
  1278. * \note
  1279. * Modify and access timestamps may be overwritten if a date time callback
  1280. * function has been set by dateTimeCallback().
  1281. *
  1282. * \return true for success, false for failure.
  1283. */
  1284. bool SdBaseFile::timestamp(SdBaseFile* file) {
  1285. dir_t* d;
  1286. dir_t dir;
  1287. // get timestamps
  1288. if (!file->dirEntry(&dir)) return false;
  1289. // update directory fields
  1290. if (!sync()) return false;
  1291. d = cacheDirEntry(SdVolume::CACHE_FOR_WRITE);
  1292. if (!d) return false;
  1293. // copy timestamps
  1294. d->lastAccessDate = dir.lastAccessDate;
  1295. d->creationDate = dir.creationDate;
  1296. d->creationTime = dir.creationTime;
  1297. d->creationTimeTenths = dir.creationTimeTenths;
  1298. d->lastWriteDate = dir.lastWriteDate;
  1299. d->lastWriteTime = dir.lastWriteTime;
  1300. // write back entry
  1301. return vol_->cacheFlush();
  1302. }
  1303. /**
  1304. * Set a file's timestamps in its directory entry.
  1305. *
  1306. * \param[in] flags Values for \a flags are constructed by a bitwise-inclusive
  1307. * OR of flags from the following list
  1308. *
  1309. * T_ACCESS - Set the file's last access date.
  1310. *
  1311. * T_CREATE - Set the file's creation date and time.
  1312. *
  1313. * T_WRITE - Set the file's last write/modification date and time.
  1314. *
  1315. * \param[in] year Valid range 1980 - 2107 inclusive.
  1316. *
  1317. * \param[in] month Valid range 1 - 12 inclusive.
  1318. *
  1319. * \param[in] day Valid range 1 - 31 inclusive.
  1320. *
  1321. * \param[in] hour Valid range 0 - 23 inclusive.
  1322. *
  1323. * \param[in] minute Valid range 0 - 59 inclusive.
  1324. *
  1325. * \param[in] second Valid range 0 - 59 inclusive
  1326. *
  1327. * \note It is possible to set an invalid date since there is no check for
  1328. * the number of days in a month.
  1329. *
  1330. * \note
  1331. * Modify and access timestamps may be overwritten if a date time callback
  1332. * function has been set by dateTimeCallback().
  1333. *
  1334. * \return true for success, false for failure.
  1335. */
  1336. bool SdBaseFile::timestamp(uint8_t flags, uint16_t year, uint8_t month,
  1337. uint8_t day, uint8_t hour, uint8_t minute, uint8_t second) {
  1338. uint16_t dirDate, dirTime;
  1339. dir_t* d;
  1340. if (!isOpen()
  1341. || year < 1980
  1342. || year > 2107
  1343. || month < 1
  1344. || month > 12
  1345. || day < 1
  1346. || day > 31
  1347. || hour > 23
  1348. || minute > 59
  1349. || second > 59) {
  1350. return false;
  1351. }
  1352. // update directory entry
  1353. if (!sync()) return false;
  1354. d = cacheDirEntry(SdVolume::CACHE_FOR_WRITE);
  1355. if (!d) return false;
  1356. dirDate = FAT_DATE(year, month, day);
  1357. dirTime = FAT_TIME(hour, minute, second);
  1358. if (flags & T_ACCESS) {
  1359. d->lastAccessDate = dirDate;
  1360. }
  1361. if (flags & T_CREATE) {
  1362. d->creationDate = dirDate;
  1363. d->creationTime = dirTime;
  1364. // seems to be units of 1/100 second not 1/10 as Microsoft states
  1365. d->creationTimeTenths = second & 1 ? 100 : 0;
  1366. }
  1367. if (flags & T_WRITE) {
  1368. d->lastWriteDate = dirDate;
  1369. d->lastWriteTime = dirTime;
  1370. }
  1371. return vol_->cacheFlush();
  1372. }
  1373. /**
  1374. * Truncate a file to a specified length. The current file position
  1375. * will be maintained if it is less than or equal to \a length otherwise
  1376. * it will be set to end of file.
  1377. *
  1378. * \param[in] length The desired length for the file.
  1379. *
  1380. * \return true for success, false for failure.
  1381. * Reasons for failure include file is read only, file is a directory,
  1382. * \a length is greater than the current file size or an I/O error occurs.
  1383. */
  1384. bool SdBaseFile::truncate(uint32_t length) {
  1385. uint32_t newPos;
  1386. // error if not a normal file or read-only
  1387. if (!isFile() || !(flags_ & O_WRITE)) return false;
  1388. // error if length is greater than current size
  1389. if (length > fileSize_) return false;
  1390. // fileSize and length are zero - nothing to do
  1391. if (fileSize_ == 0) return true;
  1392. // remember position for seek after truncation
  1393. newPos = curPosition_ > length ? length : curPosition_;
  1394. // position to last cluster in truncated file
  1395. if (!seekSet(length)) return false;
  1396. if (length == 0) {
  1397. // free all clusters
  1398. if (!vol_->freeChain(firstCluster_)) return false;
  1399. firstCluster_ = 0;
  1400. }
  1401. else {
  1402. uint32_t toFree;
  1403. if (!vol_->fatGet(curCluster_, &toFree)) return false;
  1404. if (!vol_->isEOC(toFree)) {
  1405. // free extra clusters
  1406. if (!vol_->freeChain(toFree)) return false;
  1407. // current cluster is end of chain
  1408. if (!vol_->fatPutEOC(curCluster_)) return false;
  1409. }
  1410. }
  1411. fileSize_ = length;
  1412. // need to update directory entry
  1413. flags_ |= F_FILE_DIR_DIRTY;
  1414. if (!sync()) return false;
  1415. // set file to correct position
  1416. return seekSet(newPos);
  1417. }
  1418. /**
  1419. * Write data to an open file.
  1420. *
  1421. * \note Data is moved to the cache but may not be written to the
  1422. * storage device until sync() is called.
  1423. *
  1424. * \param[in] buf Pointer to the location of the data to be written.
  1425. *
  1426. * \param[in] nbyte Number of bytes to write.
  1427. *
  1428. * \return For success write() returns the number of bytes written, always
  1429. * \a nbyte. If an error occurs, write() returns -1. Possible errors
  1430. * include write() is called before a file has been opened, write is called
  1431. * for a read-only file, device is full, a corrupt file system or an I/O error.
  1432. *
  1433. */
  1434. int16_t SdBaseFile::write(const void* buf, uint16_t nbyte) {
  1435. // convert void* to uint8_t* - must be before goto statements
  1436. const uint8_t* src = reinterpret_cast<const uint8_t*>(buf);
  1437. // number of bytes left to write - must be before goto statements
  1438. uint16_t nToWrite = nbyte;
  1439. // error if not a normal file or is read-only
  1440. if (!isFile() || !(flags_ & O_WRITE)) goto FAIL;
  1441. // seek to end of file if append flag
  1442. if ((flags_ & O_APPEND) && curPosition_ != fileSize_) {
  1443. if (!seekEnd()) goto FAIL;
  1444. }
  1445. while (nToWrite > 0) {
  1446. uint8_t blockOfCluster = vol_->blockOfCluster(curPosition_);
  1447. uint16_t blockOffset = curPosition_ & 0x1FF;
  1448. if (blockOfCluster == 0 && blockOffset == 0) {
  1449. // start of new cluster
  1450. if (curCluster_ == 0) {
  1451. if (firstCluster_ == 0) {
  1452. // allocate first cluster of file
  1453. if (!addCluster()) goto FAIL;
  1454. }
  1455. else {
  1456. curCluster_ = firstCluster_;
  1457. }
  1458. }
  1459. else {
  1460. uint32_t next;
  1461. if (!vol_->fatGet(curCluster_, &next)) goto FAIL;
  1462. if (vol_->isEOC(next)) {
  1463. // add cluster if at end of chain
  1464. if (!addCluster()) goto FAIL;
  1465. }
  1466. else {
  1467. curCluster_ = next;
  1468. }
  1469. }
  1470. }
  1471. // max space in block
  1472. uint16_t n = 512 - blockOffset;
  1473. // lesser of space and amount to write
  1474. NOMORE(n, nToWrite);
  1475. // block for data write
  1476. uint32_t block = vol_->clusterStartBlock(curCluster_) + blockOfCluster;
  1477. if (n == 512) {
  1478. // full block - don't need to use cache
  1479. if (vol_->cacheBlockNumber() == block) {
  1480. // invalidate cache if block is in cache
  1481. vol_->cacheSetBlockNumber(0xFFFFFFFF, false);
  1482. }
  1483. if (!vol_->writeBlock(block, src)) goto FAIL;
  1484. }
  1485. else {
  1486. if (blockOffset == 0 && curPosition_ >= fileSize_) {
  1487. // start of new block don't need to read into cache
  1488. if (!vol_->cacheFlush()) goto FAIL;
  1489. // set cache dirty and SD address of block
  1490. vol_->cacheSetBlockNumber(block, true);
  1491. }
  1492. else {
  1493. // rewrite part of block
  1494. if (!vol_->cacheRawBlock(block, SdVolume::CACHE_FOR_WRITE)) goto FAIL;
  1495. }
  1496. uint8_t* dst = vol_->cache()->data + blockOffset;
  1497. memcpy(dst, src, n);
  1498. }
  1499. curPosition_ += n;
  1500. src += n;
  1501. nToWrite -= n;
  1502. }
  1503. if (curPosition_ > fileSize_) {
  1504. // update fileSize and insure sync will update dir entry
  1505. fileSize_ = curPosition_;
  1506. flags_ |= F_FILE_DIR_DIRTY;
  1507. }
  1508. else if (dateTime_ && nbyte) {
  1509. // insure sync will update modified date and time
  1510. flags_ |= F_FILE_DIR_DIRTY;
  1511. }
  1512. if (flags_ & O_SYNC) {
  1513. if (!sync()) goto FAIL;
  1514. }
  1515. return nbyte;
  1516. FAIL:
  1517. // return for write error
  1518. writeError = true;
  1519. return -1;
  1520. }
  1521. #if ALLOW_DEPRECATED_FUNCTIONS
  1522. void (*SdBaseFile::oldDateTime_)(uint16_t &date, uint16_t &time) = 0;
  1523. #endif
  1524. #endif // SDSUPPORT