My Marlin configs for Fabrikator Mini and CTC i3 Pro B
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

SdBaseFile.cpp 49KB

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