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.

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