SdBaseFile.cpp 55 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828
  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. #ifdef 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. } else {
  240. if (strchr(delim, ch)) break;
  241. }
  242. }
  243. if (r < 0) {
  244. // read error
  245. return -1;
  246. }
  247. str[n] = '\0';
  248. return n;
  249. }
  250. //------------------------------------------------------------------------------
  251. /** Get a file's name
  252. *
  253. * \param[out] name An array of 13 characters for the file's name.
  254. *
  255. * \return The value one, true, is returned for success and
  256. * the value zero, false, is returned for failure.
  257. */
  258. bool SdBaseFile::getFilename(char* name) {
  259. if (!isOpen()) return false;
  260. if (isRoot()) {
  261. name[0] = '/';
  262. name[1] = '\0';
  263. return true;
  264. }
  265. // cache entry
  266. dir_t* p = cacheDirEntry(SdVolume::CACHE_FOR_READ);
  267. if (!p) return false;
  268. // format name
  269. dirName(*p, name);
  270. return true;
  271. }
  272. //------------------------------------------------------------------------------
  273. void SdBaseFile::getpos(filepos_t* pos) {
  274. pos->position = curPosition_;
  275. pos->cluster = curCluster_;
  276. }
  277. //------------------------------------------------------------------------------
  278. /** List directory contents.
  279. *
  280. * \param[in] pr Print stream for list.
  281. *
  282. * \param[in] flags The inclusive OR of
  283. *
  284. * LS_DATE - %Print file modification date
  285. *
  286. * LS_SIZE - %Print file size.
  287. *
  288. * LS_R - Recursive list of subdirectories.
  289. *
  290. * \param[in] indent Amount of space before file name. Used for recursive
  291. * list to indicate subdirectory level.
  292. */
  293. void SdBaseFile::ls(uint8_t flags, uint8_t indent) {
  294. rewind();
  295. int8_t status;
  296. while ((status = lsPrintNext( flags, indent))) {
  297. if (status > 1 && (flags & LS_R)) {
  298. uint16_t index = curPosition()/32 - 1;
  299. SdBaseFile s;
  300. if (s.open(this, index, O_READ)) s.ls( flags, indent + 2);
  301. seekSet(32 * (index + 1));
  302. }
  303. }
  304. }
  305. //------------------------------------------------------------------------------
  306. // saves 32 bytes on stack for ls recursion
  307. // return 0 - EOF, 1 - normal file, or 2 - directory
  308. int8_t SdBaseFile::lsPrintNext( uint8_t flags, uint8_t indent) {
  309. dir_t dir;
  310. uint8_t w = 0;
  311. while (1) {
  312. if (read(&dir, sizeof(dir)) != sizeof(dir)) return 0;
  313. if (dir.name[0] == DIR_NAME_FREE) return 0;
  314. // skip deleted entry and entries for . and ..
  315. if (dir.name[0] != DIR_NAME_DELETED && dir.name[0] != '.'
  316. && DIR_IS_FILE_OR_SUBDIR(&dir)) break;
  317. }
  318. // indent for dir level
  319. for (uint8_t i = 0; i < indent; i++) MYSERIAL.write(' ');
  320. // print name
  321. for (uint8_t i = 0; i < 11; i++) {
  322. if (dir.name[i] == ' ')continue;
  323. if (i == 8) {
  324. MYSERIAL.write('.');
  325. w++;
  326. }
  327. MYSERIAL.write(dir.name[i]);
  328. w++;
  329. }
  330. if (DIR_IS_SUBDIR(&dir)) {
  331. MYSERIAL.write('/');
  332. w++;
  333. }
  334. if (flags & (LS_DATE | LS_SIZE)) {
  335. while (w++ < 14) MYSERIAL.write(' ');
  336. }
  337. // print modify date/time if requested
  338. if (flags & LS_DATE) {
  339. MYSERIAL.write(' ');
  340. printFatDate( dir.lastWriteDate);
  341. MYSERIAL.write(' ');
  342. printFatTime( dir.lastWriteTime);
  343. }
  344. // print size if requested
  345. if (!DIR_IS_SUBDIR(&dir) && (flags & LS_SIZE)) {
  346. MYSERIAL.write(' ');
  347. MYSERIAL.print(dir.fileSize);
  348. }
  349. MYSERIAL.println();
  350. return DIR_IS_FILE(&dir) ? 1 : 2;
  351. }
  352. //------------------------------------------------------------------------------
  353. // format directory name field from a 8.3 name string
  354. bool SdBaseFile::make83Name(const char* str, uint8_t* name, const char** ptr) {
  355. uint8_t c;
  356. uint8_t n = 7; // max index for part before dot
  357. uint8_t i = 0;
  358. // blank fill name and extension
  359. while (i < 11) name[i++] = ' ';
  360. i = 0;
  361. while (*str != '\0' && *str != '/') {
  362. c = *str++;
  363. if (c == '.') {
  364. if (n == 10) goto fail; // only one dot allowed
  365. n = 10; // max index for full 8.3 name
  366. i = 8; // place for extension
  367. } else {
  368. // illegal FAT characters
  369. //PGM_P p = PSTR("|<>^+=?/[];,*\"\\");
  370. // 2019-08-27 really?
  371. // Microsoft defines, that only a subset of these characters is not allowed.
  372. PGM_P p = PSTR("|<>?/*\"\\");
  373. uint8_t b;
  374. while ((b = pgm_read_byte(p++))) if (b == c) goto fail;
  375. // check size and only allow ASCII printable characters
  376. if (i > n || c < 0X21 || c > 0X7E)goto fail;
  377. // only upper case allowed in 8.3 names - convert lower to upper
  378. name[i++] = (c < 'a' || c > 'z') ? (c) : (c + ('A' - 'a'));
  379. }
  380. }
  381. *ptr = str;
  382. // must have a file name, extension is optional
  383. return name[0] != ' ';
  384. fail:
  385. return false;
  386. }
  387. //------------------------------------------------------------------------------
  388. /** Make a new directory.
  389. *
  390. * \param[in] parent An open SdFat instance for the directory that will contain
  391. * the new directory.
  392. *
  393. * \param[in] path A path with a valid 8.3 DOS name for the new directory.
  394. *
  395. * \param[in] pFlag Create missing parent directories if true.
  396. *
  397. * \return The value one, true, is returned for success and
  398. * the value zero, false, is returned for failure.
  399. * Reasons for failure include this file is already open, \a parent is not a
  400. * directory, \a path is invalid or already exists in \a parent.
  401. */
  402. bool SdBaseFile::mkdir(SdBaseFile* parent, const char* path, bool pFlag) {
  403. uint8_t dname[11];
  404. SdBaseFile dir1, dir2;
  405. SdBaseFile* sub = &dir1;
  406. SdBaseFile* start = parent;
  407. if (!parent || isOpen()) goto fail;
  408. if (*path == '/') {
  409. while (*path == '/') path++;
  410. if (!parent->isRoot()) {
  411. if (!dir2.openRoot(parent->vol_)) goto fail;
  412. parent = &dir2;
  413. }
  414. }
  415. while (1) {
  416. if (!make83Name(path, dname, &path)) goto fail;
  417. while (*path == '/') path++;
  418. if (!*path) break;
  419. if (!sub->open(parent, dname, O_READ)) {
  420. if (!pFlag || !sub->mkdir(parent, dname)) {
  421. goto fail;
  422. }
  423. }
  424. if (parent != start) parent->close();
  425. parent = sub;
  426. sub = parent != &dir1 ? &dir1 : &dir2;
  427. }
  428. return mkdir(parent, dname);
  429. fail:
  430. return false;
  431. }
  432. //------------------------------------------------------------------------------
  433. bool SdBaseFile::mkdir(SdBaseFile* parent, const uint8_t dname[11]) {
  434. uint32_t block;
  435. dir_t d;
  436. dir_t* p;
  437. if (!parent->isDir()) goto fail;
  438. // create a normal file
  439. if (!open(parent, dname, O_CREAT | O_EXCL | O_RDWR)) goto fail;
  440. // convert file to directory
  441. flags_ = O_READ;
  442. type_ = FAT_FILE_TYPE_SUBDIR;
  443. // allocate and zero first cluster
  444. if (!addDirCluster())goto fail;
  445. // force entry to SD
  446. if (!sync()) goto fail;
  447. // cache entry - should already be in cache due to sync() call
  448. p = cacheDirEntry(SdVolume::CACHE_FOR_WRITE);
  449. if (!p) goto fail;
  450. // change directory entry attribute
  451. p->attributes = DIR_ATT_DIRECTORY;
  452. // make entry for '.'
  453. memcpy(&d, p, sizeof(d));
  454. d.name[0] = '.';
  455. for (uint8_t i = 1; i < 11; i++) d.name[i] = ' ';
  456. // cache block for '.' and '..'
  457. block = vol_->clusterStartBlock(firstCluster_);
  458. if (!vol_->cacheRawBlock(block, SdVolume::CACHE_FOR_WRITE)) goto fail;
  459. // copy '.' to block
  460. memcpy(&vol_->cache()->dir[0], &d, sizeof(d));
  461. // make entry for '..'
  462. d.name[1] = '.';
  463. if (parent->isRoot()) {
  464. d.firstClusterLow = 0;
  465. d.firstClusterHigh = 0;
  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. } else if (!memcmp(dname, p->name, 11)) {
  595. fileFound = true;
  596. break;
  597. }
  598. }
  599. if (fileFound) {
  600. // don't open existing file if O_EXCL
  601. if (oflag & O_EXCL) goto fail;
  602. } else {
  603. // don't create unless O_CREAT and O_WRITE
  604. if (!(oflag & O_CREAT) || !(oflag & O_WRITE)) goto fail;
  605. if (emptyFound) {
  606. index = dirIndex_;
  607. p = cacheDirEntry(SdVolume::CACHE_FOR_WRITE);
  608. if (!p) goto fail;
  609. } else {
  610. if (dirFile->type_ == FAT_FILE_TYPE_ROOT_FIXED) goto fail;
  611. // add and zero cluster for dirFile - first cluster is in cache for write
  612. if (!dirFile->addDirCluster()) goto fail;
  613. // use first entry in cluster
  614. p = dirFile->vol_->cache()->dir;
  615. index = 0;
  616. }
  617. // initialize as empty file
  618. memset(p, 0, sizeof(dir_t));
  619. memcpy(p->name, dname, 11);
  620. // set timestamps
  621. if (dateTime_) {
  622. // call user date/time function
  623. dateTime_(&p->creationDate, &p->creationTime);
  624. } else {
  625. // use default date/time
  626. p->creationDate = FAT_DEFAULT_DATE;
  627. p->creationTime = FAT_DEFAULT_TIME;
  628. }
  629. p->lastAccessDate = p->creationDate;
  630. p->lastWriteDate = p->creationDate;
  631. p->lastWriteTime = p->creationTime;
  632. // write entry to SD
  633. if (!dirFile->vol_->cacheFlush()) goto fail;
  634. }
  635. // open entry in cache
  636. return openCachedEntry(index, oflag);
  637. fail:
  638. return false;
  639. }
  640. //------------------------------------------------------------------------------
  641. /** Open a file by index.
  642. *
  643. * \param[in] dirFile An open SdFat instance for the directory.
  644. *
  645. * \param[in] index The \a index of the directory entry for the file to be
  646. * opened. The value for \a index is (directory file position)/32.
  647. *
  648. * \param[in] oflag Values for \a oflag are constructed by a bitwise-inclusive
  649. * OR of flags O_READ, O_WRITE, O_TRUNC, and O_SYNC.
  650. *
  651. * See open() by path for definition of flags.
  652. * \return true for success or false for failure.
  653. */
  654. bool SdBaseFile::open(SdBaseFile* dirFile, uint16_t index, uint8_t oflag) {
  655. dir_t* p;
  656. vol_ = dirFile->vol_;
  657. // error if already open
  658. if (isOpen() || !dirFile) goto fail;
  659. // don't open existing file if O_EXCL - user call error
  660. if (oflag & O_EXCL) goto fail;
  661. // seek to location of entry
  662. if (!dirFile->seekSet(32 * index)) goto fail;
  663. // read entry into cache
  664. p = dirFile->readDirCache();
  665. if (!p) goto fail;
  666. // error if empty slot or '.' or '..'
  667. if (p->name[0] == DIR_NAME_FREE ||
  668. p->name[0] == DIR_NAME_DELETED || p->name[0] == '.') {
  669. goto fail;
  670. }
  671. // open cached entry
  672. return openCachedEntry(index & 0XF, oflag);
  673. fail:
  674. return false;
  675. }
  676. //------------------------------------------------------------------------------
  677. // open a cached directory entry. Assumes vol_ is initialized
  678. bool SdBaseFile::openCachedEntry(uint8_t dirIndex, uint8_t oflag) {
  679. // location of entry in cache
  680. dir_t* p = &vol_->cache()->dir[dirIndex];
  681. // write or truncate is an error for a directory or read-only file
  682. if (p->attributes & (DIR_ATT_READ_ONLY | DIR_ATT_DIRECTORY)) {
  683. if (oflag & (O_WRITE | O_TRUNC)) goto fail;
  684. }
  685. // remember location of directory entry on SD
  686. dirBlock_ = vol_->cacheBlockNumber();
  687. dirIndex_ = dirIndex;
  688. // copy first cluster number for directory fields
  689. firstCluster_ = (uint32_t)p->firstClusterHigh << 16;
  690. firstCluster_ |= p->firstClusterLow;
  691. // make sure it is a normal file or subdirectory
  692. if (DIR_IS_FILE(p)) {
  693. fileSize_ = p->fileSize;
  694. type_ = FAT_FILE_TYPE_NORMAL;
  695. } else if (DIR_IS_SUBDIR(p)) {
  696. if (!vol_->chainSize(firstCluster_, &fileSize_)) goto fail;
  697. type_ = FAT_FILE_TYPE_SUBDIR;
  698. } else {
  699. goto fail;
  700. }
  701. // save open flags for read/write
  702. flags_ = oflag & F_OFLAG;
  703. // set to start of file
  704. curCluster_ = 0;
  705. curPosition_ = 0;
  706. if ((oflag & O_TRUNC) && !truncate(0)) return false;
  707. return oflag & O_AT_END ? seekEnd(0) : true;
  708. fail:
  709. type_ = FAT_FILE_TYPE_CLOSED;
  710. return false;
  711. }
  712. //------------------------------------------------------------------------------
  713. /** Open the next file or subdirectory in a directory.
  714. *
  715. * \param[in] dirFile An open SdFat instance for the directory containing the
  716. * file to be opened.
  717. *
  718. * \param[in] oflag Values for \a oflag are constructed by a bitwise-inclusive
  719. * OR of flags O_READ, O_WRITE, O_TRUNC, and O_SYNC.
  720. *
  721. * See open() by path for definition of flags.
  722. * \return true for success or false for failure.
  723. */
  724. bool SdBaseFile::openNext(SdBaseFile* dirFile, uint8_t oflag) {
  725. dir_t* p;
  726. uint8_t index;
  727. if (!dirFile) goto fail;
  728. // error if already open
  729. if (isOpen()) goto fail;
  730. vol_ = dirFile->vol_;
  731. while (1) {
  732. index = 0XF & (dirFile->curPosition_ >> 5);
  733. // read entry into cache
  734. p = dirFile->readDirCache();
  735. if (!p) goto fail;
  736. // done if last entry
  737. if (p->name[0] == DIR_NAME_FREE) goto fail;
  738. // skip empty slot or '.' or '..'
  739. if (p->name[0] == DIR_NAME_DELETED || p->name[0] == '.') {
  740. continue;
  741. }
  742. // must be file or dir
  743. if (DIR_IS_FILE_OR_SUBDIR(p)) {
  744. return openCachedEntry(index, oflag);
  745. }
  746. }
  747. fail:
  748. return false;
  749. }
  750. //------------------------------------------------------------------------------
  751. /** Open a directory's parent directory.
  752. *
  753. * \param[in] dir Parent of this directory will be opened. Must not be root.
  754. *
  755. * \return The value one, true, is returned for success and
  756. * the value zero, false, is returned for failure.
  757. */
  758. bool SdBaseFile::openParent(SdBaseFile* dir) {
  759. dir_t entry;
  760. dir_t* p;
  761. SdBaseFile file;
  762. uint32_t c;
  763. uint32_t cluster;
  764. uint32_t lbn;
  765. // error if already open or dir is root or dir is not a directory
  766. if (isOpen() || !dir || dir->isRoot() || !dir->isDir()) goto fail;
  767. vol_ = dir->vol_;
  768. // position to '..'
  769. if (!dir->seekSet(32)) goto fail;
  770. // read '..' entry
  771. if (dir->read(&entry, sizeof(entry)) != 32) goto fail;
  772. // verify it is '..'
  773. if (entry.name[0] != '.' || entry.name[1] != '.') goto fail;
  774. // start cluster for '..'
  775. cluster = entry.firstClusterLow;
  776. cluster |= (uint32_t)entry.firstClusterHigh << 16;
  777. if (cluster == 0) return openRoot(vol_);
  778. // start block for '..'
  779. lbn = vol_->clusterStartBlock(cluster);
  780. // first block of parent dir
  781. if (!vol_->cacheRawBlock(lbn, SdVolume::CACHE_FOR_READ)) {
  782. goto fail;
  783. }
  784. p = &vol_->cacheBuffer_.dir[1];
  785. // verify name for '../..'
  786. if (p->name[0] != '.' || p->name[1] != '.') goto fail;
  787. // '..' is pointer to first cluster of parent. open '../..' to find parent
  788. if (p->firstClusterHigh == 0 && p->firstClusterLow == 0) {
  789. if (!file.openRoot(dir->volume())) goto fail;
  790. } else {
  791. if (!file.openCachedEntry(1, O_READ)) goto fail;
  792. }
  793. // search for parent in '../..'
  794. do {
  795. if (file.readDir(&entry, NULL) != 32) goto fail;
  796. c = entry.firstClusterLow;
  797. c |= (uint32_t)entry.firstClusterHigh << 16;
  798. } while (c != cluster);
  799. // open parent
  800. return open(&file, file.curPosition()/32 - 1, O_READ);
  801. fail:
  802. return false;
  803. }
  804. //------------------------------------------------------------------------------
  805. /** Open a volume's root directory.
  806. *
  807. * \param[in] vol The FAT volume containing the root directory to be opened.
  808. *
  809. * \return The value one, true, is returned for success and
  810. * the value zero, false, is returned for failure.
  811. * Reasons for failure include the file is already open, the FAT volume has
  812. * not been initialized or it a FAT12 volume.
  813. */
  814. bool SdBaseFile::openRoot(SdVolume* vol) {
  815. // error if file is already open
  816. if (isOpen()) goto fail;
  817. if (vol->fatType() == 16 || (FAT12_SUPPORT && vol->fatType() == 12)) {
  818. type_ = FAT_FILE_TYPE_ROOT_FIXED;
  819. firstCluster_ = 0;
  820. fileSize_ = 32 * vol->rootDirEntryCount();
  821. } else if (vol->fatType() == 32) {
  822. type_ = FAT_FILE_TYPE_ROOT32;
  823. firstCluster_ = vol->rootDirStart();
  824. if (!vol->chainSize(firstCluster_, &fileSize_)) goto fail;
  825. } else {
  826. // volume is not initialized, invalid, or FAT12 without support
  827. return false;
  828. }
  829. vol_ = vol;
  830. // read only
  831. flags_ = O_READ;
  832. // set to start of file
  833. curCluster_ = 0;
  834. curPosition_ = 0;
  835. // root has no directory entry
  836. dirBlock_ = 0;
  837. dirIndex_ = 0;
  838. return true;
  839. fail:
  840. return false;
  841. }
  842. //------------------------------------------------------------------------------
  843. /** Return the next available byte without consuming it.
  844. *
  845. * \return The byte if no error and not at eof else -1;
  846. */
  847. int SdBaseFile::peek() {
  848. filepos_t pos;
  849. getpos(&pos);
  850. int c = read();
  851. if (c >= 0) setpos(&pos);
  852. return c;
  853. }
  854. //------------------------------------------------------------------------------
  855. /** %Print the name field of a directory entry in 8.3 format.
  856. * \param[in] pr Print stream for output.
  857. * \param[in] dir The directory structure containing the name.
  858. * \param[in] width Blank fill name if length is less than \a width.
  859. * \param[in] printSlash Print '/' after directory names if true.
  860. */
  861. void SdBaseFile::printDirName(const dir_t& dir,
  862. uint8_t width, bool printSlash) {
  863. uint8_t w = 0;
  864. for (uint8_t i = 0; i < 11; i++) {
  865. if (dir.name[i] == ' ')continue;
  866. if (i == 8) {
  867. MYSERIAL.write('.');
  868. w++;
  869. }
  870. MYSERIAL.write(dir.name[i]);
  871. w++;
  872. }
  873. if (DIR_IS_SUBDIR(&dir) && printSlash) {
  874. MYSERIAL.write('/');
  875. w++;
  876. }
  877. while (w < width) {
  878. MYSERIAL.write(' ');
  879. w++;
  880. }
  881. }
  882. //------------------------------------------------------------------------------
  883. // print uint8_t with width 2
  884. static void print2u( uint8_t v) {
  885. if (v < 10) MYSERIAL.write('0');
  886. MYSERIAL.print(v, DEC);
  887. }
  888. //------------------------------------------------------------------------------
  889. /** %Print a directory date field to Serial.
  890. *
  891. * Format is yyyy-mm-dd.
  892. *
  893. * \param[in] fatDate The date field from a directory entry.
  894. */
  895. //------------------------------------------------------------------------------
  896. /** %Print a directory date field.
  897. *
  898. * Format is yyyy-mm-dd.
  899. *
  900. * \param[in] pr Print stream for output.
  901. * \param[in] fatDate The date field from a directory entry.
  902. */
  903. void SdBaseFile::printFatDate(uint16_t fatDate) {
  904. MYSERIAL.print(FAT_YEAR(fatDate));
  905. MYSERIAL.write('-');
  906. print2u( FAT_MONTH(fatDate));
  907. MYSERIAL.write('-');
  908. print2u( FAT_DAY(fatDate));
  909. }
  910. //------------------------------------------------------------------------------
  911. /** %Print a directory time field.
  912. *
  913. * Format is hh:mm:ss.
  914. *
  915. * \param[in] pr Print stream for output.
  916. * \param[in] fatTime The time field from a directory entry.
  917. */
  918. void SdBaseFile::printFatTime( uint16_t fatTime) {
  919. print2u( FAT_HOUR(fatTime));
  920. MYSERIAL.write(':');
  921. print2u( FAT_MINUTE(fatTime));
  922. MYSERIAL.write(':');
  923. print2u( FAT_SECOND(fatTime));
  924. }
  925. //------------------------------------------------------------------------------
  926. /** Print a file's name to Serial
  927. *
  928. * \return The value one, true, is returned for success and
  929. * the value zero, false, is returned for failure.
  930. */
  931. bool SdBaseFile::printName() {
  932. char name[13];
  933. if (!getFilename(name)) return false;
  934. MYSERIAL.print(name);
  935. return true;
  936. }
  937. //------------------------------------------------------------------------------
  938. /** Read the next byte from a file.
  939. *
  940. * \return For success read returns the next byte in the file as an int.
  941. * If an error occurs or end of file is reached -1 is returned.
  942. */
  943. int16_t SdBaseFile::read() {
  944. uint8_t b;
  945. return read(&b, 1) == 1 ? b : -1;
  946. }
  947. //------------------------------------------------------------------------------
  948. /** Read data from a file starting at the current position.
  949. *
  950. * \param[out] buf Pointer to the location that will receive the data.
  951. *
  952. * \param[in] nbyte Maximum number of bytes to read.
  953. *
  954. * \return For success read() returns the number of bytes read.
  955. * A value less than \a nbyte, including zero, will be returned
  956. * if end of file is reached.
  957. * If an error occurs, read() returns -1. Possible errors include
  958. * read() called before a file has been opened, corrupt file system
  959. * or an I/O error occurred.
  960. */
  961. int16_t SdBaseFile::read(void* buf, uint16_t nbyte) {
  962. uint8_t* dst = reinterpret_cast<uint8_t*>(buf);
  963. uint16_t offset;
  964. uint16_t toRead;
  965. uint32_t block; // raw device block number
  966. // error if not open or write only
  967. if (!isOpen() || !(flags_ & O_READ)) goto fail;
  968. // max bytes left in file
  969. if (nbyte >= (fileSize_ - curPosition_)) {
  970. nbyte = fileSize_ - curPosition_;
  971. }
  972. // amount left to read
  973. toRead = nbyte;
  974. while (toRead > 0) {
  975. offset = curPosition_ & 0X1FF; // offset in block
  976. if (type_ == FAT_FILE_TYPE_ROOT_FIXED) {
  977. block = vol_->rootDirStart() + (curPosition_ >> 9);
  978. } else {
  979. uint8_t blockOfCluster = vol_->blockOfCluster(curPosition_);
  980. if (offset == 0 && blockOfCluster == 0) {
  981. // start of new cluster
  982. if (curPosition_ == 0) {
  983. // use first cluster in file
  984. curCluster_ = firstCluster_;
  985. } else {
  986. // get next cluster from FAT
  987. if (!vol_->fatGet(curCluster_, &curCluster_)) goto fail;
  988. }
  989. }
  990. block = vol_->clusterStartBlock(curCluster_) + blockOfCluster;
  991. }
  992. uint16_t n = toRead;
  993. // amount to be read from current block
  994. if (n > (512 - offset)) n = 512 - offset;
  995. // no buffering needed if n == 512
  996. if (n == 512 && block != vol_->cacheBlockNumber()) {
  997. if (!vol_->readBlock(block, dst)) goto fail;
  998. } else {
  999. // read block to cache and copy data to caller
  1000. if (!vol_->cacheRawBlock(block, SdVolume::CACHE_FOR_READ)) goto fail;
  1001. uint8_t* src = vol_->cache()->data + offset;
  1002. memcpy(dst, src, n);
  1003. }
  1004. dst += n;
  1005. curPosition_ += n;
  1006. toRead -= n;
  1007. }
  1008. return nbyte;
  1009. fail:
  1010. return -1;
  1011. }
  1012. //------------------------------------------------------------------------------
  1013. /** Read the next directory entry from a directory file.
  1014. *
  1015. * \param[out] dir The dir_t struct that will receive the data.
  1016. *
  1017. * \return For success readDir() returns the number of bytes read.
  1018. * A value of zero will be returned if end of file is reached.
  1019. * If an error occurs, readDir() returns -1. Possible errors include
  1020. * readDir() called before a directory has been opened, this is not
  1021. * a directory file or an I/O error occurred.
  1022. */
  1023. int8_t SdBaseFile::readDir(dir_t* dir, char* longFilename) {
  1024. int16_t n;
  1025. // if not a directory file or miss-positioned return an error
  1026. if (!isDir() || (0X1F & curPosition_)) return -1;
  1027. //If we have a longFilename buffer, mark it as invalid. If we find a long filename it will be filled automaticly.
  1028. if (longFilename != NULL)
  1029. {
  1030. longFilename[0] = '\0';
  1031. }
  1032. while (1) {
  1033. n = read(dir, sizeof(dir_t));
  1034. if (n != sizeof(dir_t)) return n == 0 ? 0 : -1;
  1035. // last entry if DIR_NAME_FREE
  1036. if (dir->name[0] == DIR_NAME_FREE) return 0;
  1037. // skip empty entries and entry for . and ..
  1038. if (dir->name[0] == DIR_NAME_DELETED || dir->name[0] == '.') continue;
  1039. //Fill the long filename if we have a long filename entry,
  1040. // long filename entries are stored before the actual filename.
  1041. if (DIR_IS_LONG_NAME(dir) && longFilename != NULL)
  1042. {
  1043. vfat_t *VFAT = (vfat_t*)dir;
  1044. //Sanity check the VFAT entry. The first cluster is always set to zero. And th esequence number should be higher then 0
  1045. if (VFAT->firstClusterLow == 0 && (VFAT->sequenceNumber & 0x1F) > 0 && (VFAT->sequenceNumber & 0x1F) <= MAX_VFAT_ENTRIES)
  1046. {
  1047. //TODO: Store the filename checksum to verify if a none-long filename aware system modified the file table.
  1048. n = ((VFAT->sequenceNumber & 0x1F) - 1) * 13;
  1049. longFilename[n+0] = VFAT->name1[0];
  1050. longFilename[n+1] = VFAT->name1[1];
  1051. longFilename[n+2] = VFAT->name1[2];
  1052. longFilename[n+3] = VFAT->name1[3];
  1053. longFilename[n+4] = VFAT->name1[4];
  1054. longFilename[n+5] = VFAT->name2[0];
  1055. longFilename[n+6] = VFAT->name2[1];
  1056. longFilename[n+7] = VFAT->name2[2];
  1057. longFilename[n+8] = VFAT->name2[3];
  1058. longFilename[n+9] = VFAT->name2[4];
  1059. longFilename[n+10] = VFAT->name2[5];
  1060. longFilename[n+11] = VFAT->name3[0];
  1061. longFilename[n+12] = VFAT->name3[1];
  1062. //If this VFAT entry is the last one, add a NUL terminator at the end of the string
  1063. if (VFAT->sequenceNumber & 0x40)
  1064. longFilename[n+13] = '\0';
  1065. }
  1066. }
  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(filepos_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
  1661. #endif