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

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