My Marlin configs for Fabrikator Mini and CTC i3 Pro B
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

SdBaseFile.cpp 55KB

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