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

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