| 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 "SdFat.h" |
| 21 | #ifdef __AVR__ |
| 22 | #include <avr/pgmspace.h> |
| 23 | #endif |
| 24 | #include <Arduino.h> |
| 25 | //------------------------------------------------------------------------------ |
| 26 | // callback function for date/time |
| 27 | void (*SdFile::dateTime_)(uint16_t* date, uint16_t* time) = NULL; |
| 28 | |
| 29 | #if ALLOW_DEPRECATED_FUNCTIONS |
| 30 | // suppress cpplint warnings with NOLINT comment |
| 31 | void (*SdFile::oldDateTime_)(uint16_t& date, uint16_t& time) = NULL; // NOLINT |
| 32 | #endif // ALLOW_DEPRECATED_FUNCTIONS |
| 33 | //------------------------------------------------------------------------------ |
| 34 | // add a cluster to a file |
| 35 | uint8_t SdFile::addCluster() { |
| 36 | if (!vol_->allocContiguous(1, &curCluster_)) return false; |
| 37 | |
| 38 | // if first cluster of file link to directory entry |
| 39 | if (firstCluster_ == 0) { |
| 40 | firstCluster_ = curCluster_; |
| 41 | flags_ |= F_FILE_DIR_DIRTY; |
| 42 | } |
| 43 | return true; |
| 44 | } |
| 45 | //------------------------------------------------------------------------------ |
| 46 | // Add a cluster to a directory file and zero the cluster. |
| 47 | // return with first block of cluster in the cache |
| 48 | uint8_t SdFile::addDirCluster(void) { |
| 49 | if (!addCluster()) return false; |
| 50 | |
| 51 | // zero data in cluster insure first cluster is in cache |
| 52 | uint32_t block = vol_->clusterStartBlock(curCluster_); |
| 53 | for (uint8_t i = vol_->blocksPerCluster_; i != 0; i--) { |
| 54 | if (!SdVolume::cacheZeroBlock(block + i - 1)) return false; |
| 55 | } |
| 56 | // Increase directory file size by cluster size |
| 57 | fileSize_ += 512UL << vol_->clusterSizeShift_; |
| 58 | return true; |
| 59 | } |
| 60 | //------------------------------------------------------------------------------ |
| 61 | // cache a file's directory entry |
| 62 | // return pointer to cached entry or null for failure |
| 63 | dir_t* SdFile::cacheDirEntry(uint8_t action) { |
| 64 | if (!SdVolume::cacheRawBlock(dirBlock_, action)) return NULL; |
| 65 | return SdVolume::cacheBuffer_.dir + dirIndex_; |
| 66 | } |
| 67 | //------------------------------------------------------------------------------ |
| 68 | /** |
| 69 | * Close a file and force cached data and directory information |
| 70 | * to be written to the storage device. |
| 71 | * |
| 72 | * \return The value one, true, is returned for success and |
| 73 | * the value zero, false, is returned for failure. |
| 74 | * Reasons for failure include no file is open or an I/O error. |
| 75 | */ |
| 76 | uint8_t SdFile::close(void) { |
| 77 | if (!sync())return false; |
| 78 | type_ = FAT_FILE_TYPE_CLOSED; |
| 79 | return true; |
| 80 | } |
| 81 | //------------------------------------------------------------------------------ |
| 82 | /** |
| 83 | * Check for contiguous file and return its raw block range. |
| 84 | * |
| 85 | * \param[out] bgnBlock the first block address for the file. |
| 86 | * \param[out] endBlock the last block address for the file. |
| 87 | * |
| 88 | * \return The value one, true, is returned for success and |
| 89 | * the value zero, false, is returned for failure. |
| 90 | * Reasons for failure include file is not contiguous, file has zero length |
| 91 | * or an I/O error occurred. |
| 92 | */ |
| 93 | uint8_t SdFile::contiguousRange(uint32_t* bgnBlock, uint32_t* endBlock) { |
| 94 | // error if no blocks |
| 95 | if (firstCluster_ == 0) return false; |
| 96 | |
| 97 | for (uint32_t c = firstCluster_; ; c++) { |
| 98 | uint32_t next; |
| 99 | if (!vol_->fatGet(c, &next)) return false; |
| 100 | |
| 101 | // check for contiguous |
| 102 | if (next != (c + 1)) { |
| 103 | // error if not end of chain |
| 104 | if (!vol_->isEOC(next)) return false; |
| 105 | *bgnBlock = vol_->clusterStartBlock(firstCluster_); |
| 106 | *endBlock = vol_->clusterStartBlock(c) |
| 107 | + vol_->blocksPerCluster_ - 1; |
| 108 | return true; |
| 109 | } |
| 110 | } |
| 111 | } |
| 112 | //------------------------------------------------------------------------------ |
| 113 | /** |
| 114 | * Create and open a new contiguous file of a specified size. |
| 115 | * |
| 116 | * \note This function only supports short DOS 8.3 names. |
| 117 | * See open() for more information. |
| 118 | * |
| 119 | * \param[in] dirFile The directory where the file will be created. |
| 120 | * \param[in] fileName A valid DOS 8.3 file name. |
| 121 | * \param[in] size The desired file size. |
| 122 | * |
| 123 | * \return The value one, true, is returned for success and |
| 124 | * the value zero, false, is returned for failure. |
| 125 | * Reasons for failure include \a fileName contains |
| 126 | * an invalid DOS 8.3 file name, the FAT volume has not been initialized, |
| 127 | * a file is already open, the file already exists, the root |
| 128 | * directory is full or an I/O error. |
| 129 | * |
| 130 | */ |
| 131 | uint8_t SdFile::createContiguous(SdFile* dirFile, |
| 132 | const char* fileName, uint32_t size) { |
| 133 | // don't allow zero length file |
| 134 | if (size == 0) return false; |
| 135 | if (!open(dirFile, fileName, O_CREAT | O_EXCL | O_RDWR)) return false; |
| 136 | |
| 137 | // calculate number of clusters needed |
| 138 | uint32_t count = ((size - 1) >> (vol_->clusterSizeShift_ + 9)) + 1; |
| 139 | |
| 140 | // allocate clusters |
| 141 | if (!vol_->allocContiguous(count, &firstCluster_)) { |
| 142 | remove(); |
| 143 | return false; |
| 144 | } |
| 145 | fileSize_ = size; |
| 146 | |
| 147 | // insure sync() will update dir entry |
| 148 | flags_ |= F_FILE_DIR_DIRTY; |
| 149 | return sync(); |
| 150 | } |
| 151 | //------------------------------------------------------------------------------ |
| 152 | /** |
| 153 | * Return a files directory entry |
| 154 | * |
| 155 | * \param[out] dir Location for return of the files directory entry. |
| 156 | * |
| 157 | * \return The value one, true, is returned for success and |
| 158 | * the value zero, false, is returned for failure. |
| 159 | */ |
| 160 | uint8_t SdFile::dirEntry(dir_t* dir) { |
| 161 | // make sure fields on SD are correct |
| 162 | if (!sync()) return false; |
| 163 | |
| 164 | // read entry |
| 165 | dir_t* p = cacheDirEntry(SdVolume::CACHE_FOR_READ); |
| 166 | if (!p) return false; |
| 167 | |
| 168 | // copy to caller's struct |
| 169 | memcpy(dir, p, sizeof(dir_t)); |
| 170 | return true; |
| 171 | } |
| 172 | //------------------------------------------------------------------------------ |
| 173 | /** |
| 174 | * Format the name field of \a dir into the 13 byte array |
| 175 | * \a name in standard 8.3 short name format. |
| 176 | * |
| 177 | * \param[in] dir The directory structure containing the name. |
| 178 | * \param[out] name A 13 byte char array for the formatted name. |
| 179 | */ |
| 180 | void SdFile::dirName(const dir_t& dir, char* name) { |
| 181 | uint8_t j = 0; |
| 182 | for (uint8_t i = 0; i < 11; i++) { |
| 183 | if (dir.name[i] == ' ')continue; |
| 184 | if (i == 8) name[j++] = '.'; |
| 185 | name[j++] = dir.name[i]; |
| 186 | } |
| 187 | name[j] = 0; |
| 188 | } |
| 189 | //------------------------------------------------------------------------------ |
| 190 | /** List directory contents to Serial. |
| 191 | * |
| 192 | * \param[in] flags The inclusive OR of |
| 193 | * |
| 194 | * LS_DATE - %Print file modification date |
| 195 | * |
| 196 | * LS_SIZE - %Print file size. |
| 197 | * |
| 198 | * LS_R - Recursive list of subdirectories. |
| 199 | * |
| 200 | * \param[in] indent Amount of space before file name. Used for recursive |
| 201 | * list to indicate subdirectory level. |
| 202 | */ |
| 203 | void SdFile::ls(uint8_t flags, uint8_t indent) { |
| 204 | dir_t* p; |
| 205 | |
| 206 | rewind(); |
| 207 | while ((p = readDirCache())) { |
| 208 | // done if past last used entry |
| 209 | if (p->name[0] == DIR_NAME_FREE) break; |
| 210 | |
| 211 | // skip deleted entry and entries for . and .. |
| 212 | if (p->name[0] == DIR_NAME_DELETED || p->name[0] == '.') continue; |
| 213 | |
| 214 | // only list subdirectories and files |
| 215 | if (!DIR_IS_FILE_OR_SUBDIR(p)) continue; |
| 216 | |
| 217 | // print any indent spaces |
| 218 | for (int8_t i = 0; i < indent; i++) Serial.print(' '); |
| 219 | |
| 220 | // print file name with possible blank fill |
| 221 | printDirName(*p, flags & (LS_DATE | LS_SIZE) ? 14 : 0); |
| 222 | |
| 223 | // print modify date/time if requested |
| 224 | if (flags & LS_DATE) { |
| 225 | printFatDate(p->lastWriteDate); |
| 226 | Serial.print(' '); |
| 227 | printFatTime(p->lastWriteTime); |
| 228 | } |
| 229 | // print size if requested |
| 230 | if (!DIR_IS_SUBDIR(p) && (flags & LS_SIZE)) { |
| 231 | Serial.print(' '); |
| 232 | Serial.print(p->fileSize); |
| 233 | } |
| 234 | Serial.println(); |
| 235 | |
| 236 | // list subdirectory content if requested |
| 237 | if ((flags & LS_R) && DIR_IS_SUBDIR(p)) { |
| 238 | uint16_t index = curPosition()/32 - 1; |
| 239 | SdFile s; |
| 240 | if (s.open(this, index, O_READ)) s.ls(flags, indent + 2); |
| 241 | seekSet(32 * (index + 1)); |
| 242 | } |
| 243 | } |
| 244 | } |
| 245 | //------------------------------------------------------------------------------ |
| 246 | // format directory name field from a 8.3 name string |
| 247 | uint8_t SdFile::make83Name(const char* str, uint8_t* name) { |
| 248 | uint8_t c; |
| 249 | uint8_t n = 7; // max index for part before dot |
| 250 | uint8_t i = 0; |
| 251 | // blank fill name and extension |
| 252 | while (i < 11) name[i++] = ' '; |
| 253 | i = 0; |
| 254 | while ((c = *str++) != '\0') { |
| 255 | if (c == '.') { |
| 256 | if (n == 10) return false; // only one dot allowed |
| 257 | n = 10; // max index for full 8.3 name |
| 258 | i = 8; // place for extension |
| 259 | } else { |
| 260 | // illegal FAT characters |
| 261 | uint8_t b; |
| 262 | #if defined(__AVR__) |
| 263 | PGM_P p = PSTR("|<>^+=?/[];,*\"\\"); |
| 264 | while ((b = pgm_read_byte(p++))) if (b == c) return false; |
| 265 | #elif defined(__arm__) |
| 266 | const uint8_t valid[] = "|<>^+=?/[];,*\"\\"; |
| 267 | const uint8_t *p = valid; |
| 268 | while ((b = *p++)) if (b == c) return false; |
| 269 | #endif |
| 270 | // check size and only allow ASCII printable characters |
| 271 | if (i > n || c < 0X21 || c > 0X7E)return false; |
| 272 | // only upper case allowed in 8.3 names - convert lower to upper |
| 273 | name[i++] = c < 'a' || c > 'z' ? c : c + ('A' - 'a'); |
| 274 | } |
| 275 | } |
| 276 | // must have a file name, extension is optional |
| 277 | return name[0] != ' '; |
| 278 | } |
| 279 | //------------------------------------------------------------------------------ |
| 280 | /** Make a new directory. |
| 281 | * |
| 282 | * \param[in] dir An open SdFat instance for the directory that will containing |
| 283 | * the new directory. |
| 284 | * |
| 285 | * \param[in] dirName A valid 8.3 DOS name for the new directory. |
| 286 | * |
| 287 | * \return The value one, true, is returned for success and |
| 288 | * the value zero, false, is returned for failure. |
| 289 | * Reasons for failure include this SdFile is already open, \a dir is not a |
| 290 | * directory, \a dirName is invalid or already exists in \a dir. |
| 291 | */ |
| 292 | uint8_t SdFile::makeDir(SdFile* dir, const char* dirName) { |
| 293 | dir_t d; |
| 294 | |
| 295 | // create a normal file |
| 296 | if (!open(dir, dirName, O_CREAT | O_EXCL | O_RDWR)) return false; |
| 297 | |
| 298 | // convert SdFile to directory |
| 299 | flags_ = O_READ; |
| 300 | type_ = FAT_FILE_TYPE_SUBDIR; |
| 301 | |
| 302 | // allocate and zero first cluster |
| 303 | if (!addDirCluster())return false; |
| 304 | |
| 305 | // force entry to SD |
| 306 | if (!sync()) return false; |
| 307 | |
| 308 | // cache entry - should already be in cache due to sync() call |
| 309 | dir_t* p = cacheDirEntry(SdVolume::CACHE_FOR_WRITE); |
| 310 | if (!p) return false; |
| 311 | |
| 312 | // change directory entry attribute |
| 313 | p->attributes = DIR_ATT_DIRECTORY; |
| 314 | |
| 315 | // make entry for '.' |
| 316 | memcpy(&d, p, sizeof(d)); |
| 317 | for (uint8_t i = 1; i < 11; i++) d.name[i] = ' '; |
| 318 | d.name[0] = '.'; |
| 319 | |
| 320 | // cache block for '.' and '..' |
| 321 | uint32_t block = vol_->clusterStartBlock(firstCluster_); |
| 322 | if (!SdVolume::cacheRawBlock(block, SdVolume::CACHE_FOR_WRITE)) return false; |
| 323 | |
| 324 | // copy '.' to block |
| 325 | memcpy(&SdVolume::cacheBuffer_.dir[0], &d, sizeof(d)); |
| 326 | |
| 327 | // make entry for '..' |
| 328 | d.name[1] = '.'; |
| 329 | if (dir->isRoot()) { |
| 330 | d.firstClusterLow = 0; |
| 331 | d.firstClusterHigh = 0; |
| 332 | } else { |
| 333 | d.firstClusterLow = dir->firstCluster_ & 0XFFFF; |
| 334 | d.firstClusterHigh = dir->firstCluster_ >> 16; |
| 335 | } |
| 336 | // copy '..' to block |
| 337 | memcpy(&SdVolume::cacheBuffer_.dir[1], &d, sizeof(d)); |
| 338 | |
| 339 | // set position after '..' |
| 340 | curPosition_ = 2 * sizeof(d); |
| 341 | |
| 342 | // write first block |
| 343 | return SdVolume::cacheFlush(); |
| 344 | } |
| 345 | //------------------------------------------------------------------------------ |
| 346 | /** |
| 347 | * Open a file or directory by name. |
| 348 | * |
| 349 | * \param[in] dirFile An open SdFat instance for the directory containing the |
| 350 | * file to be opened. |
| 351 | * |
| 352 | * \param[in] fileName A valid 8.3 DOS name for a file to be opened. |
| 353 | * |
| 354 | * \param[in] oflag Values for \a oflag are constructed by a bitwise-inclusive |
| 355 | * OR of flags from the following list |
| 356 | * |
| 357 | * O_READ - Open for reading. |
| 358 | * |
| 359 | * O_RDONLY - Same as O_READ. |
| 360 | * |
| 361 | * O_WRITE - Open for writing. |
| 362 | * |
| 363 | * O_WRONLY - Same as O_WRITE. |
| 364 | * |
| 365 | * O_RDWR - Open for reading and writing. |
| 366 | * |
| 367 | * O_APPEND - If set, the file offset shall be set to the end of the |
| 368 | * file prior to each write. |
| 369 | * |
| 370 | * O_CREAT - If the file exists, this flag has no effect except as noted |
| 371 | * under O_EXCL below. Otherwise, the file shall be created |
| 372 | * |
| 373 | * O_EXCL - If O_CREAT and O_EXCL are set, open() shall fail if the file exists. |
| 374 | * |
| 375 | * O_SYNC - Call sync() after each write. This flag should not be used with |
| 376 | * write(uint8_t), write_P(PGM_P), writeln_P(PGM_P), or the Arduino Print class. |
| 377 | * These functions do character at a time writes so sync() will be called |
| 378 | * after each byte. |
| 379 | * |
| 380 | * O_TRUNC - If the file exists and is a regular file, and the file is |
| 381 | * successfully opened and is not read only, its length shall be truncated to 0. |
| 382 | * |
| 383 | * \note Directory files must be opened read only. Write and truncation is |
| 384 | * not allowed for directory files. |
| 385 | * |
| 386 | * \return The value one, true, is returned for success and |
| 387 | * the value zero, false, is returned for failure. |
| 388 | * Reasons for failure include this SdFile is already open, \a difFile is not |
| 389 | * a directory, \a fileName is invalid, the file does not exist |
| 390 | * or can't be opened in the access mode specified by oflag. |
| 391 | */ |
| 392 | uint8_t SdFile::open(SdFile* dirFile, const char* fileName, uint8_t oflag) { |
| 393 | uint8_t dname[11]; |
| 394 | dir_t* p; |
| 395 | |
| 396 | // error if already open |
| 397 | if (isOpen())return false; |
| 398 | |
| 399 | if (!make83Name(fileName, dname)) return false; |
| 400 | vol_ = dirFile->vol_; |
| 401 | dirFile->rewind(); |
| 402 | |
| 403 | // bool for empty entry found |
| 404 | uint8_t emptyFound = false; |
| 405 | |
| 406 | // search for file |
| 407 | while (dirFile->curPosition_ < dirFile->fileSize_) { |
| 408 | uint8_t index = 0XF & (dirFile->curPosition_ >> 5); |
| 409 | p = dirFile->readDirCache(); |
| 410 | if (p == NULL) return false; |
| 411 | |
| 412 | if (p->name[0] == DIR_NAME_FREE || p->name[0] == DIR_NAME_DELETED) { |
| 413 | // remember first empty slot |
| 414 | if (!emptyFound) { |
| 415 | emptyFound = true; |
| 416 | dirIndex_ = index; |
| 417 | dirBlock_ = SdVolume::cacheBlockNumber_; |
| 418 | } |
| 419 | // done if no entries follow |
| 420 | if (p->name[0] == DIR_NAME_FREE) break; |
| 421 | } else if (!memcmp(dname, p->name, 11)) { |
| 422 | // don't open existing file if O_CREAT and O_EXCL |
| 423 | if ((oflag & (O_CREAT | O_EXCL)) == (O_CREAT | O_EXCL)) return false; |
| 424 | |
| 425 | // open found file |
| 426 | return openCachedEntry(0XF & index, oflag); |
| 427 | } |
| 428 | } |
| 429 | // only create file if O_CREAT and O_WRITE |
| 430 | if ((oflag & (O_CREAT | O_WRITE)) != (O_CREAT | O_WRITE)) return false; |
| 431 | |
| 432 | // cache found slot or add cluster if end of file |
| 433 | if (emptyFound) { |
| 434 | p = cacheDirEntry(SdVolume::CACHE_FOR_WRITE); |
| 435 | if (!p) return false; |
| 436 | } else { |
| 437 | if (dirFile->type_ == FAT_FILE_TYPE_ROOT16) return false; |
| 438 | |
| 439 | // add and zero cluster for dirFile - first cluster is in cache for write |
| 440 | if (!dirFile->addDirCluster()) return false; |
| 441 | |
| 442 | // use first entry in cluster |
| 443 | dirIndex_ = 0; |
| 444 | p = SdVolume::cacheBuffer_.dir; |
| 445 | } |
| 446 | // initialize as empty file |
| 447 | memset(p, 0, sizeof(dir_t)); |
| 448 | memcpy(p->name, dname, 11); |
| 449 | |
| 450 | // set timestamps |
| 451 | if (dateTime_) { |
| 452 | // call user function |
| 453 | dateTime_(&p->creationDate, &p->creationTime); |
| 454 | } else { |
| 455 | // use default date/time |
| 456 | p->creationDate = FAT_DEFAULT_DATE; |
| 457 | p->creationTime = FAT_DEFAULT_TIME; |
| 458 | } |
| 459 | p->lastAccessDate = p->creationDate; |
| 460 | p->lastWriteDate = p->creationDate; |
| 461 | p->lastWriteTime = p->creationTime; |
| 462 | |
| 463 | // force write of entry to SD |
| 464 | if (!SdVolume::cacheFlush()) return false; |
| 465 | |
| 466 | // open entry in cache |
| 467 | return openCachedEntry(dirIndex_, oflag); |
| 468 | } |
| 469 | //------------------------------------------------------------------------------ |
| 470 | /** |
| 471 | * Open a file by index. |
| 472 | * |
| 473 | * \param[in] dirFile An open SdFat instance for the directory. |
| 474 | * |
| 475 | * \param[in] index The \a index of the directory entry for the file to be |
| 476 | * opened. The value for \a index is (directory file position)/32. |
| 477 | * |
| 478 | * \param[in] oflag Values for \a oflag are constructed by a bitwise-inclusive |
| 479 | * OR of flags O_READ, O_WRITE, O_TRUNC, and O_SYNC. |
| 480 | * |
| 481 | * See open() by fileName for definition of flags and return values. |
| 482 | * |
| 483 | */ |
| 484 | uint8_t SdFile::open(SdFile* dirFile, uint16_t index, uint8_t oflag) { |
| 485 | // error if already open |
| 486 | if (isOpen())return false; |
| 487 | |
| 488 | // don't open existing file if O_CREAT and O_EXCL - user call error |
| 489 | if ((oflag & (O_CREAT | O_EXCL)) == (O_CREAT | O_EXCL)) return false; |
| 490 | |
| 491 | vol_ = dirFile->vol_; |
| 492 | |
| 493 | // seek to location of entry |
| 494 | if (!dirFile->seekSet(32 * index)) return false; |
| 495 | |
| 496 | // read entry into cache |
| 497 | dir_t* p = dirFile->readDirCache(); |
| 498 | if (p == NULL) return false; |
| 499 | |
| 500 | // error if empty slot or '.' or '..' |
| 501 | if (p->name[0] == DIR_NAME_FREE || |
| 502 | p->name[0] == DIR_NAME_DELETED || p->name[0] == '.') { |
| 503 | return false; |
| 504 | } |
| 505 | // open cached entry |
| 506 | return openCachedEntry(index & 0XF, oflag); |
| 507 | } |
| 508 | //------------------------------------------------------------------------------ |
| 509 | // open a cached directory entry. Assumes vol_ is initializes |
| 510 | uint8_t SdFile::openCachedEntry(uint8_t dirIndex, uint8_t oflag) { |
| 511 | // location of entry in cache |
| 512 | dir_t* p = SdVolume::cacheBuffer_.dir + dirIndex; |
| 513 | |
| 514 | // write or truncate is an error for a directory or read-only file |
| 515 | if (p->attributes & (DIR_ATT_READ_ONLY | DIR_ATT_DIRECTORY)) { |
| 516 | if (oflag & (O_WRITE | O_TRUNC)) return false; |
| 517 | } |
| 518 | // remember location of directory entry on SD |
| 519 | dirIndex_ = dirIndex; |
| 520 | dirBlock_ = SdVolume::cacheBlockNumber_; |
| 521 | |
| 522 | // copy first cluster number for directory fields |
| 523 | firstCluster_ = (uint32_t)p->firstClusterHigh << 16; |
| 524 | firstCluster_ |= p->firstClusterLow; |
| 525 | |
| 526 | // make sure it is a normal file or subdirectory |
| 527 | if (DIR_IS_FILE(p)) { |
| 528 | fileSize_ = p->fileSize; |
| 529 | type_ = FAT_FILE_TYPE_NORMAL; |
| 530 | } else if (DIR_IS_SUBDIR(p)) { |
| 531 | if (!vol_->chainSize(firstCluster_, &fileSize_)) return false; |
| 532 | type_ = FAT_FILE_TYPE_SUBDIR; |
| 533 | } else { |
| 534 | return false; |
| 535 | } |
| 536 | // save open flags for read/write |
| 537 | flags_ = oflag & (O_ACCMODE | O_SYNC | O_APPEND); |
| 538 | |
| 539 | // set to start of file |
| 540 | curCluster_ = 0; |
| 541 | curPosition_ = 0; |
| 542 | |
| 543 | // truncate file to zero length if requested |
| 544 | if (oflag & O_TRUNC) return truncate(0); |
| 545 | return true; |
| 546 | } |
| 547 | //------------------------------------------------------------------------------ |
| 548 | /** |
| 549 | * Open a volume's root directory. |
| 550 | * |
| 551 | * \param[in] vol The FAT volume containing the root directory to be opened. |
| 552 | * |
| 553 | * \return The value one, true, is returned for success and |
| 554 | * the value zero, false, is returned for failure. |
| 555 | * Reasons for failure include the FAT volume has not been initialized |
| 556 | * or it a FAT12 volume. |
| 557 | */ |
| 558 | uint8_t SdFile::openRoot(SdVolume* vol) { |
| 559 | // error if file is already open |
| 560 | if (isOpen()) return false; |
| 561 | |
| 562 | if (vol->fatType() == 16) { |
| 563 | type_ = FAT_FILE_TYPE_ROOT16; |
| 564 | firstCluster_ = 0; |
| 565 | fileSize_ = 32 * vol->rootDirEntryCount(); |
| 566 | } else if (vol->fatType() == 32) { |
| 567 | type_ = FAT_FILE_TYPE_ROOT32; |
| 568 | firstCluster_ = vol->rootDirStart(); |
| 569 | if (!vol->chainSize(firstCluster_, &fileSize_)) return false; |
| 570 | } else { |
| 571 | // volume is not initialized or FAT12 |
| 572 | return false; |
| 573 | } |
| 574 | vol_ = vol; |
| 575 | // read only |
| 576 | flags_ = O_READ; |
| 577 | |
| 578 | // set to start of file |
| 579 | curCluster_ = 0; |
| 580 | curPosition_ = 0; |
| 581 | |
| 582 | // root has no directory entry |
| 583 | dirBlock_ = 0; |
| 584 | dirIndex_ = 0; |
| 585 | return true; |
| 586 | } |
| 587 | //------------------------------------------------------------------------------ |
| 588 | /** %Print the name field of a directory entry in 8.3 format to Serial. |
| 589 | * |
| 590 | * \param[in] dir The directory structure containing the name. |
| 591 | * \param[in] width Blank fill name if length is less than \a width. |
| 592 | */ |
| 593 | void SdFile::printDirName(const dir_t& dir, uint8_t width) { |
| 594 | uint8_t w = 0; |
| 595 | for (uint8_t i = 0; i < 11; i++) { |
| 596 | if (dir.name[i] == ' ')continue; |
| 597 | if (i == 8) { |
| 598 | Serial.print('.'); |
| 599 | w++; |
| 600 | } |
| 601 | Serial.write(dir.name[i]); |
| 602 | w++; |
| 603 | } |
| 604 | if (DIR_IS_SUBDIR(&dir)) { |
| 605 | Serial.print('/'); |
| 606 | w++; |
| 607 | } |
| 608 | while (w < width) { |
| 609 | Serial.print(' '); |
| 610 | w++; |
| 611 | } |
| 612 | } |
| 613 | //------------------------------------------------------------------------------ |
| 614 | /** %Print a directory date field to Serial. |
| 615 | * |
| 616 | * Format is yyyy-mm-dd. |
| 617 | * |
| 618 | * \param[in] fatDate The date field from a directory entry. |
| 619 | */ |
| 620 | void SdFile::printFatDate(uint16_t fatDate) { |
| 621 | Serial.print(FAT_YEAR(fatDate)); |
| 622 | Serial.print('-'); |
| 623 | printTwoDigits(FAT_MONTH(fatDate)); |
| 624 | Serial.print('-'); |
| 625 | printTwoDigits(FAT_DAY(fatDate)); |
| 626 | } |
| 627 | //------------------------------------------------------------------------------ |
| 628 | /** %Print a directory time field to Serial. |
| 629 | * |
| 630 | * Format is hh:mm:ss. |
| 631 | * |
| 632 | * \param[in] fatTime The time field from a directory entry. |
| 633 | */ |
| 634 | void SdFile::printFatTime(uint16_t fatTime) { |
| 635 | printTwoDigits(FAT_HOUR(fatTime)); |
| 636 | Serial.print(':'); |
| 637 | printTwoDigits(FAT_MINUTE(fatTime)); |
| 638 | Serial.print(':'); |
| 639 | printTwoDigits(FAT_SECOND(fatTime)); |
| 640 | } |
| 641 | //------------------------------------------------------------------------------ |
| 642 | /** %Print a value as two digits to Serial. |
| 643 | * |
| 644 | * \param[in] v Value to be printed, 0 <= \a v <= 99 |
| 645 | */ |
| 646 | void SdFile::printTwoDigits(uint8_t v) { |
| 647 | char str[3]; |
| 648 | str[0] = '0' + v/10; |
| 649 | str[1] = '0' + v % 10; |
| 650 | str[2] = 0; |
| 651 | Serial.print(str); |
| 652 | } |
| 653 | //------------------------------------------------------------------------------ |
| 654 | /** |
| 655 | * Read data from a file starting at the current position. |
| 656 | * |
| 657 | * \param[out] buf Pointer to the location that will receive the data. |
| 658 | * |
| 659 | * \param[in] nbyte Maximum number of bytes to read. |
| 660 | * |
| 661 | * \return For success read() returns the number of bytes read. |
| 662 | * A value less than \a nbyte, including zero, will be returned |
| 663 | * if end of file is reached. |
| 664 | * If an error occurs, read() returns -1. Possible errors include |
| 665 | * read() called before a file has been opened, corrupt file system |
| 666 | * or an I/O error occurred. |
| 667 | */ |
| 668 | int16_t SdFile::read(void* buf, uint16_t nbyte) { |
| 669 | uint8_t* dst = reinterpret_cast<uint8_t*>(buf); |
| 670 | |
| 671 | // error if not open or write only |
| 672 | if (!isOpen() || !(flags_ & O_READ)) return -1; |
| 673 | |
| 674 | // max bytes left in file |
| 675 | if (nbyte > (fileSize_ - curPosition_)) nbyte = fileSize_ - curPosition_; |
| 676 | |
| 677 | // amount left to read |
| 678 | uint16_t toRead = nbyte; |
| 679 | while (toRead > 0) { |
| 680 | uint32_t block; // raw device block number |
| 681 | uint16_t offset = curPosition_ & 0X1FF; // offset in block |
| 682 | if (type_ == FAT_FILE_TYPE_ROOT16) { |
| 683 | block = vol_->rootDirStart() + (curPosition_ >> 9); |
| 684 | } else { |
| 685 | uint8_t blockOfCluster = vol_->blockOfCluster(curPosition_); |
| 686 | if (offset == 0 && blockOfCluster == 0) { |
| 687 | // start of new cluster |
| 688 | if (curPosition_ == 0) { |
| 689 | // use first cluster in file |
| 690 | curCluster_ = firstCluster_; |
| 691 | } else { |
| 692 | // get next cluster from FAT |
| 693 | if (!vol_->fatGet(curCluster_, &curCluster_)) return -1; |
| 694 | } |
| 695 | } |
| 696 | block = vol_->clusterStartBlock(curCluster_) + blockOfCluster; |
| 697 | } |
| 698 | uint16_t n = toRead; |
| 699 | |
| 700 | // amount to be read from current block |
| 701 | if (n > (512 - offset)) n = 512 - offset; |
| 702 | |
| 703 | // no buffering needed if n == 512 or user requests no buffering |
| 704 | if ((unbufferedRead() || n == 512) && |
| 705 | block != SdVolume::cacheBlockNumber_) { |
| 706 | if (!vol_->readData(block, offset, n, dst)) return -1; |
| 707 | dst += n; |
| 708 | } else { |
| 709 | // read block to cache and copy data to caller |
| 710 | if (!SdVolume::cacheRawBlock(block, SdVolume::CACHE_FOR_READ)) return -1; |
| 711 | uint8_t* src = SdVolume::cacheBuffer_.data + offset; |
| 712 | uint8_t* end = src + n; |
| 713 | while (src != end) *dst++ = *src++; |
| 714 | } |
| 715 | curPosition_ += n; |
| 716 | toRead -= n; |
| 717 | } |
| 718 | return nbyte; |
| 719 | } |
| 720 | //------------------------------------------------------------------------------ |
| 721 | /** |
| 722 | * Read the next directory entry from a directory file. |
| 723 | * |
| 724 | * \param[out] dir The dir_t struct that will receive the data. |
| 725 | * |
| 726 | * \return For success readDir() returns the number of bytes read. |
| 727 | * A value of zero will be returned if end of file is reached. |
| 728 | * If an error occurs, readDir() returns -1. Possible errors include |
| 729 | * readDir() called before a directory has been opened, this is not |
| 730 | * a directory file or an I/O error occurred. |
| 731 | */ |
| 732 | int8_t SdFile::readDir(dir_t* dir) { |
| 733 | int8_t n; |
| 734 | // if not a directory file or miss-positioned return an error |
| 735 | if (!isDir() || (0X1F & curPosition_)) return -1; |
| 736 | |
| 737 | while ((n = read(dir, sizeof(dir_t))) == sizeof(dir_t)) { |
| 738 | // last entry if DIR_NAME_FREE |
| 739 | if (dir->name[0] == DIR_NAME_FREE) break; |
| 740 | // skip empty entries and entry for . and .. |
| 741 | if (dir->name[0] == DIR_NAME_DELETED || dir->name[0] == '.') continue; |
| 742 | // return if normal file or subdirectory |
| 743 | if (DIR_IS_FILE_OR_SUBDIR(dir)) return n; |
| 744 | } |
| 745 | // error, end of file, or past last entry |
| 746 | return n < 0 ? -1 : 0; |
| 747 | } |
| 748 | //------------------------------------------------------------------------------ |
| 749 | // Read next directory entry into the cache |
| 750 | // Assumes file is correctly positioned |
| 751 | dir_t* SdFile::readDirCache(void) { |
| 752 | // error if not directory |
| 753 | if (!isDir()) return NULL; |
| 754 | |
| 755 | // index of entry in cache |
| 756 | uint8_t i = (curPosition_ >> 5) & 0XF; |
| 757 | |
| 758 | // use read to locate and cache block |
| 759 | if (read() < 0) return NULL; |
| 760 | |
| 761 | // advance to next entry |
| 762 | curPosition_ += 31; |
| 763 | |
| 764 | // return pointer to entry |
| 765 | return (SdVolume::cacheBuffer_.dir + i); |
| 766 | } |
| 767 | //------------------------------------------------------------------------------ |
| 768 | /** |
| 769 | * Remove a file. |
| 770 | * |
| 771 | * The directory entry and all data for the file are deleted. |
| 772 | * |
| 773 | * \note This function should not be used to delete the 8.3 version of a |
| 774 | * file that has a long name. For example if a file has the long name |
| 775 | * "New Text Document.txt" you should not delete the 8.3 name "NEWTEX~1.TXT". |
| 776 | * |
| 777 | * \return The value one, true, is returned for success and |
| 778 | * the value zero, false, is returned for failure. |
| 779 | * Reasons for failure include the file read-only, is a directory, |
| 780 | * or an I/O error occurred. |
| 781 | */ |
| 782 | uint8_t SdFile::remove(void) { |
| 783 | // free any clusters - will fail if read-only or directory |
| 784 | if (!truncate(0)) return false; |
| 785 | |
| 786 | // cache directory entry |
| 787 | dir_t* d = cacheDirEntry(SdVolume::CACHE_FOR_WRITE); |
| 788 | if (!d) return false; |
| 789 | |
| 790 | // mark entry deleted |
| 791 | d->name[0] = DIR_NAME_DELETED; |
| 792 | |
| 793 | // set this SdFile closed |
| 794 | type_ = FAT_FILE_TYPE_CLOSED; |
| 795 | |
| 796 | // write entry to SD |
| 797 | return SdVolume::cacheFlush(); |
| 798 | } |
| 799 | //------------------------------------------------------------------------------ |
| 800 | /** |
| 801 | * Remove a file. |
| 802 | * |
| 803 | * The directory entry and all data for the file are deleted. |
| 804 | * |
| 805 | * \param[in] dirFile The directory that contains the file. |
| 806 | * \param[in] fileName The name of the file to be removed. |
| 807 | * |
| 808 | * \note This function should not be used to delete the 8.3 version of a |
| 809 | * file that has a long name. For example if a file has the long name |
| 810 | * "New Text Document.txt" you should not delete the 8.3 name "NEWTEX~1.TXT". |
| 811 | * |
| 812 | * \return The value one, true, is returned for success and |
| 813 | * the value zero, false, is returned for failure. |
| 814 | * Reasons for failure include the file is a directory, is read only, |
| 815 | * \a dirFile is not a directory, \a fileName is not found |
| 816 | * or an I/O error occurred. |
| 817 | */ |
| 818 | uint8_t SdFile::remove(SdFile* dirFile, const char* fileName) { |
| 819 | SdFile file; |
| 820 | if (!file.open(dirFile, fileName, O_WRITE)) return false; |
| 821 | return file.remove(); |
| 822 | } |
| 823 | //------------------------------------------------------------------------------ |
| 824 | /** Remove a directory file. |
| 825 | * |
| 826 | * The directory file will be removed only if it is empty and is not the |
| 827 | * root directory. rmDir() follows DOS and Windows and ignores the |
| 828 | * read-only attribute for the directory. |
| 829 | * |
| 830 | * \note This function should not be used to delete the 8.3 version of a |
| 831 | * directory that has a long name. For example if a directory has the |
| 832 | * long name "New folder" you should not delete the 8.3 name "NEWFOL~1". |
| 833 | * |
| 834 | * \return The value one, true, is returned for success and |
| 835 | * the value zero, false, is returned for failure. |
| 836 | * Reasons for failure include the file is not a directory, is the root |
| 837 | * directory, is not empty, or an I/O error occurred. |
| 838 | */ |
| 839 | uint8_t SdFile::rmDir(void) { |
| 840 | // must be open subdirectory |
| 841 | if (!isSubDir()) return false; |
| 842 | |
| 843 | rewind(); |
| 844 | |
| 845 | // make sure directory is empty |
| 846 | while (curPosition_ < fileSize_) { |
| 847 | dir_t* p = readDirCache(); |
| 848 | if (p == NULL) return false; |
| 849 | // done if past last used entry |
| 850 | if (p->name[0] == DIR_NAME_FREE) break; |
| 851 | // skip empty slot or '.' or '..' |
| 852 | if (p->name[0] == DIR_NAME_DELETED || p->name[0] == '.') continue; |
| 853 | // error not empty |
| 854 | if (DIR_IS_FILE_OR_SUBDIR(p)) return false; |
| 855 | } |
| 856 | // convert empty directory to normal file for remove |
| 857 | type_ = FAT_FILE_TYPE_NORMAL; |
| 858 | flags_ |= O_WRITE; |
| 859 | return remove(); |
| 860 | } |
| 861 | //------------------------------------------------------------------------------ |
| 862 | /** Recursively delete a directory and all contained files. |
| 863 | * |
| 864 | * This is like the Unix/Linux 'rm -rf *' if called with the root directory |
| 865 | * hence the name. |
| 866 | * |
| 867 | * Warning - This will remove all contents of the directory including |
| 868 | * subdirectories. The directory will then be removed if it is not root. |
| 869 | * The read-only attribute for files will be ignored. |
| 870 | * |
| 871 | * \note This function should not be used to delete the 8.3 version of |
| 872 | * a directory that has a long name. See remove() and rmDir(). |
| 873 | * |
| 874 | * \return The value one, true, is returned for success and |
| 875 | * the value zero, false, is returned for failure. |
| 876 | */ |
| 877 | uint8_t SdFile::rmRfStar(void) { |
| 878 | rewind(); |
| 879 | while (curPosition_ < fileSize_) { |
| 880 | SdFile f; |
| 881 | |
| 882 | // remember position |
| 883 | uint16_t index = curPosition_/32; |
| 884 | |
| 885 | dir_t* p = readDirCache(); |
| 886 | if (!p) return false; |
| 887 | |
| 888 | // done if past last entry |
| 889 | if (p->name[0] == DIR_NAME_FREE) break; |
| 890 | |
| 891 | // skip empty slot or '.' or '..' |
| 892 | if (p->name[0] == DIR_NAME_DELETED || p->name[0] == '.') continue; |
| 893 | |
| 894 | // skip if part of long file name or volume label in root |
| 895 | if (!DIR_IS_FILE_OR_SUBDIR(p)) continue; |
| 896 | |
| 897 | if (!f.open(this, index, O_READ)) return false; |
| 898 | if (f.isSubDir()) { |
| 899 | // recursively delete |
| 900 | if (!f.rmRfStar()) return false; |
| 901 | } else { |
| 902 | // ignore read-only |
| 903 | f.flags_ |= O_WRITE; |
| 904 | if (!f.remove()) return false; |
| 905 | } |
| 906 | // position to next entry if required |
| 907 | if (curPosition_ != (32u*(index + 1))) { |
| 908 | if (!seekSet(32u*(index + 1))) return false; |
| 909 | } |
| 910 | } |
| 911 | // don't try to delete root |
| 912 | if (isRoot()) return true; |
| 913 | return rmDir(); |
| 914 | } |
| 915 | //------------------------------------------------------------------------------ |
| 916 | /** |
| 917 | * Sets a file's position. |
| 918 | * |
| 919 | * \param[in] pos The new position in bytes from the beginning of the file. |
| 920 | * |
| 921 | * \return The value one, true, is returned for success and |
| 922 | * the value zero, false, is returned for failure. |
| 923 | */ |
| 924 | uint8_t SdFile::seekSet(uint32_t pos) { |
| 925 | // error if file not open or seek past end of file |
| 926 | if (!isOpen() || pos > fileSize_) return false; |
| 927 | |
| 928 | if (type_ == FAT_FILE_TYPE_ROOT16) { |
| 929 | curPosition_ = pos; |
| 930 | return true; |
| 931 | } |
| 932 | if (pos == 0) { |
| 933 | // set position to start of file |
| 934 | curCluster_ = 0; |
| 935 | curPosition_ = 0; |
| 936 | return true; |
| 937 | } |
| 938 | // calculate cluster index for cur and new position |
| 939 | uint32_t nCur = (curPosition_ - 1) >> (vol_->clusterSizeShift_ + 9); |
| 940 | uint32_t nNew = (pos - 1) >> (vol_->clusterSizeShift_ + 9); |
| 941 | |
| 942 | if (nNew < nCur || curPosition_ == 0) { |
| 943 | // must follow chain from first cluster |
| 944 | curCluster_ = firstCluster_; |
| 945 | } else { |
| 946 | // advance from curPosition |
| 947 | nNew -= nCur; |
| 948 | } |
| 949 | while (nNew--) { |
| 950 | if (!vol_->fatGet(curCluster_, &curCluster_)) return false; |
| 951 | } |
| 952 | curPosition_ = pos; |
| 953 | return true; |
| 954 | } |
| 955 | //------------------------------------------------------------------------------ |
| 956 | /** |
| 957 | * The sync() call causes all modified data and directory fields |
| 958 | * to be written to the storage device. |
| 959 | * |
| 960 | * \return The value one, true, is returned for success and |
| 961 | * the value zero, false, is returned for failure. |
| 962 | * Reasons for failure include a call to sync() before a file has been |
| 963 | * opened or an I/O error. |
| 964 | */ |
| 965 | uint8_t SdFile::sync(void) { |
| 966 | // only allow open files and directories |
| 967 | if (!isOpen()) return false; |
| 968 | |
| 969 | if (flags_ & F_FILE_DIR_DIRTY) { |
| 970 | dir_t* d = cacheDirEntry(SdVolume::CACHE_FOR_WRITE); |
| 971 | if (!d) return false; |
| 972 | |
| 973 | // do not set filesize for dir files |
| 974 | if (!isDir()) d->fileSize = fileSize_; |
| 975 | |
| 976 | // update first cluster fields |
| 977 | d->firstClusterLow = firstCluster_ & 0XFFFF; |
| 978 | d->firstClusterHigh = firstCluster_ >> 16; |
| 979 | |
| 980 | // set modify time if user supplied a callback date/time function |
| 981 | if (dateTime_) { |
| 982 | dateTime_(&d->lastWriteDate, &d->lastWriteTime); |
| 983 | d->lastAccessDate = d->lastWriteDate; |
| 984 | } |
| 985 | // clear directory dirty |
| 986 | flags_ &= ~F_FILE_DIR_DIRTY; |
| 987 | } |
| 988 | return SdVolume::cacheFlush(); |
| 989 | } |
| 990 | //------------------------------------------------------------------------------ |
| 991 | /** |
| 992 | * Set a file's timestamps in its directory entry. |
| 993 | * |
| 994 | * \param[in] flags Values for \a flags are constructed by a bitwise-inclusive |
| 995 | * OR of flags from the following list |
| 996 | * |
| 997 | * T_ACCESS - Set the file's last access date. |
| 998 | * |
| 999 | * T_CREATE - Set the file's creation date and time. |
| 1000 | * |
| 1001 | * T_WRITE - Set the file's last write/modification date and time. |
| 1002 | * |
| 1003 | * \param[in] year Valid range 1980 - 2107 inclusive. |
| 1004 | * |
| 1005 | * \param[in] month Valid range 1 - 12 inclusive. |
| 1006 | * |
| 1007 | * \param[in] day Valid range 1 - 31 inclusive. |
| 1008 | * |
| 1009 | * \param[in] hour Valid range 0 - 23 inclusive. |
| 1010 | * |
| 1011 | * \param[in] minute Valid range 0 - 59 inclusive. |
| 1012 | * |
| 1013 | * \param[in] second Valid range 0 - 59 inclusive |
| 1014 | * |
| 1015 | * \note It is possible to set an invalid date since there is no check for |
| 1016 | * the number of days in a month. |
| 1017 | * |
| 1018 | * \note |
| 1019 | * Modify and access timestamps may be overwritten if a date time callback |
| 1020 | * function has been set by dateTimeCallback(). |
| 1021 | * |
| 1022 | * \return The value one, true, is returned for success and |
| 1023 | * the value zero, false, is returned for failure. |
| 1024 | */ |
| 1025 | uint8_t SdFile::timestamp(uint8_t flags, uint16_t year, uint8_t month, |
| 1026 | uint8_t day, uint8_t hour, uint8_t minute, uint8_t second) { |
| 1027 | if (!isOpen() |
| 1028 | || year < 1980 |
| 1029 | || year > 2107 |
| 1030 | || month < 1 |
| 1031 | || month > 12 |
| 1032 | || day < 1 |
| 1033 | || day > 31 |
| 1034 | || hour > 23 |
| 1035 | || minute > 59 |
| 1036 | || second > 59) { |
| 1037 | return false; |
| 1038 | } |
| 1039 | dir_t* d = cacheDirEntry(SdVolume::CACHE_FOR_WRITE); |
| 1040 | if (!d) return false; |
| 1041 | |
| 1042 | uint16_t dirDate = FAT_DATE(year, month, day); |
| 1043 | uint16_t dirTime = FAT_TIME(hour, minute, second); |
| 1044 | if (flags & T_ACCESS) { |
| 1045 | d->lastAccessDate = dirDate; |
| 1046 | } |
| 1047 | if (flags & T_CREATE) { |
| 1048 | d->creationDate = dirDate; |
| 1049 | d->creationTime = dirTime; |
| 1050 | // seems to be units of 1/100 second not 1/10 as Microsoft states |
| 1051 | d->creationTimeTenths = second & 1 ? 100 : 0; |
| 1052 | } |
| 1053 | if (flags & T_WRITE) { |
| 1054 | d->lastWriteDate = dirDate; |
| 1055 | d->lastWriteTime = dirTime; |
| 1056 | } |
| 1057 | SdVolume::cacheSetDirty(); |
| 1058 | return sync(); |
| 1059 | } |
| 1060 | //------------------------------------------------------------------------------ |
| 1061 | /** |
| 1062 | * Truncate a file to a specified length. The current file position |
| 1063 | * will be maintained if it is less than or equal to \a length otherwise |
| 1064 | * it will be set to end of file. |
| 1065 | * |
| 1066 | * \param[in] length The desired length for the file. |
| 1067 | * |
| 1068 | * \return The value one, true, is returned for success and |
| 1069 | * the value zero, false, is returned for failure. |
| 1070 | * Reasons for failure include file is read only, file is a directory, |
| 1071 | * \a length is greater than the current file size or an I/O error occurs. |
| 1072 | */ |
| 1073 | uint8_t SdFile::truncate(uint32_t length) { |
| 1074 | // error if not a normal file or read-only |
| 1075 | if (!isFile() || !(flags_ & O_WRITE)) return false; |
| 1076 | |
| 1077 | // error if length is greater than current size |
| 1078 | if (length > fileSize_) return false; |
| 1079 | |
| 1080 | // fileSize and length are zero - nothing to do |
| 1081 | if (fileSize_ == 0) return true; |
| 1082 | |
| 1083 | // remember position for seek after truncation |
| 1084 | uint32_t newPos = curPosition_ > length ? length : curPosition_; |
| 1085 | |
| 1086 | // position to last cluster in truncated file |
| 1087 | if (!seekSet(length)) return false; |
| 1088 | |
| 1089 | if (length == 0) { |
| 1090 | // free all clusters |
| 1091 | if (!vol_->freeChain(firstCluster_)) return false; |
| 1092 | firstCluster_ = 0; |
| 1093 | } else { |
| 1094 | uint32_t toFree; |
| 1095 | if (!vol_->fatGet(curCluster_, &toFree)) return false; |
| 1096 | |
| 1097 | if (!vol_->isEOC(toFree)) { |
| 1098 | // free extra clusters |
| 1099 | if (!vol_->freeChain(toFree)) return false; |
| 1100 | |
| 1101 | // current cluster is end of chain |
| 1102 | if (!vol_->fatPutEOC(curCluster_)) return false; |
| 1103 | } |
| 1104 | } |
| 1105 | fileSize_ = length; |
| 1106 | |
| 1107 | // need to update directory entry |
| 1108 | flags_ |= F_FILE_DIR_DIRTY; |
| 1109 | |
| 1110 | if (!sync()) return false; |
| 1111 | |
| 1112 | // set file to correct position |
| 1113 | return seekSet(newPos); |
| 1114 | } |
| 1115 | //------------------------------------------------------------------------------ |
| 1116 | /** |
| 1117 | * Write data to an open file. |
| 1118 | * |
| 1119 | * \note Data is moved to the cache but may not be written to the |
| 1120 | * storage device until sync() is called. |
| 1121 | * |
| 1122 | * \param[in] buf Pointer to the location of the data to be written. |
| 1123 | * |
| 1124 | * \param[in] nbyte Number of bytes to write. |
| 1125 | * |
| 1126 | * \return For success write() returns the number of bytes written, always |
| 1127 | * \a nbyte. If an error occurs, write() returns 0. Possible errors |
| 1128 | * include write() is called before a file has been opened, write is called |
| 1129 | * for a read-only file, device is full, a corrupt file system or an I/O error. |
| 1130 | * |
| 1131 | */ |
| 1132 | size_t SdFile::write(const void* buf, uint16_t nbyte) { |
| 1133 | // convert void* to uint8_t* - must be before goto statements |
| 1134 | const uint8_t* src = reinterpret_cast<const uint8_t*>(buf); |
| 1135 | |
| 1136 | // number of bytes left to write - must be before goto statements |
| 1137 | uint16_t nToWrite = nbyte; |
| 1138 | |
| 1139 | // error if not a normal file or is read-only |
| 1140 | if (!isFile() || !(flags_ & O_WRITE)) goto writeErrorReturn; |
| 1141 | |
| 1142 | // seek to end of file if append flag |
| 1143 | if ((flags_ & O_APPEND) && curPosition_ != fileSize_) { |
| 1144 | if (!seekEnd()) goto writeErrorReturn; |
| 1145 | } |
| 1146 | |
| 1147 | while (nToWrite > 0) { |
| 1148 | uint8_t blockOfCluster = vol_->blockOfCluster(curPosition_); |
| 1149 | uint16_t blockOffset = curPosition_ & 0X1FF; |
| 1150 | if (blockOfCluster == 0 && blockOffset == 0) { |
| 1151 | // start of new cluster |
| 1152 | if (curCluster_ == 0) { |
| 1153 | if (firstCluster_ == 0) { |
| 1154 | // allocate first cluster of file |
| 1155 | if (!addCluster()) goto writeErrorReturn; |
| 1156 | } else { |
| 1157 | curCluster_ = firstCluster_; |
| 1158 | } |
| 1159 | } else { |
| 1160 | uint32_t next; |
| 1161 | if (!vol_->fatGet(curCluster_, &next)) return false; |
| 1162 | if (vol_->isEOC(next)) { |
| 1163 | // add cluster if at end of chain |
| 1164 | if (!addCluster()) goto writeErrorReturn; |
| 1165 | } else { |
| 1166 | curCluster_ = next; |
| 1167 | } |
| 1168 | } |
| 1169 | } |
| 1170 | // max space in block |
| 1171 | uint16_t n = 512 - blockOffset; |
| 1172 | |
| 1173 | // lesser of space and amount to write |
| 1174 | if (n > nToWrite) n = nToWrite; |
| 1175 | |
| 1176 | // block for data write |
| 1177 | uint32_t block = vol_->clusterStartBlock(curCluster_) + blockOfCluster; |
| 1178 | if (n == 512) { |
| 1179 | // full block - don't need to use cache |
| 1180 | // invalidate cache if block is in cache |
| 1181 | if (SdVolume::cacheBlockNumber_ == block) { |
| 1182 | SdVolume::cacheBlockNumber_ = 0XFFFFFFFF; |
| 1183 | } |
| 1184 | if (!vol_->writeBlock(block, src)) goto writeErrorReturn; |
| 1185 | src += 512; |
| 1186 | } else { |
| 1187 | if (blockOffset == 0 && curPosition_ >= fileSize_) { |
| 1188 | // start of new block don't need to read into cache |
| 1189 | if (!SdVolume::cacheFlush()) goto writeErrorReturn; |
| 1190 | SdVolume::cacheBlockNumber_ = block; |
| 1191 | SdVolume::cacheSetDirty(); |
| 1192 | } else { |
| 1193 | // rewrite part of block |
| 1194 | if (!SdVolume::cacheRawBlock(block, SdVolume::CACHE_FOR_WRITE)) { |
| 1195 | goto writeErrorReturn; |
| 1196 | } |
| 1197 | } |
| 1198 | uint8_t* dst = SdVolume::cacheBuffer_.data + blockOffset; |
| 1199 | uint8_t* end = dst + n; |
| 1200 | while (dst != end) *dst++ = *src++; |
| 1201 | } |
| 1202 | nToWrite -= n; |
| 1203 | curPosition_ += n; |
| 1204 | } |
| 1205 | if (curPosition_ > fileSize_) { |
| 1206 | // update fileSize and insure sync will update dir entry |
| 1207 | fileSize_ = curPosition_; |
| 1208 | flags_ |= F_FILE_DIR_DIRTY; |
| 1209 | } else if (dateTime_ && nbyte) { |
| 1210 | // insure sync will update modified date and time |
| 1211 | flags_ |= F_FILE_DIR_DIRTY; |
| 1212 | } |
| 1213 | |
| 1214 | if (flags_ & O_SYNC) { |
| 1215 | if (!sync()) goto writeErrorReturn; |
| 1216 | } |
| 1217 | return nbyte; |
| 1218 | |
| 1219 | writeErrorReturn: |
| 1220 | // return for write error |
| 1221 | //writeError = true; |
| 1222 | setWriteError(); |
| 1223 | return 0; |
| 1224 | } |
| 1225 | //------------------------------------------------------------------------------ |
| 1226 | /** |
| 1227 | * Write a byte to a file. Required by the Arduino Print class. |
| 1228 | * |
| 1229 | * Use SdFile::writeError to check for errors. |
| 1230 | */ |
| 1231 | size_t SdFile::write(uint8_t b) { |
| 1232 | return write(&b, 1); |
| 1233 | } |
| 1234 | //------------------------------------------------------------------------------ |
| 1235 | /** |
| 1236 | * Write a string to a file. Used by the Arduino Print class. |
| 1237 | * |
| 1238 | * Use SdFile::writeError to check for errors. |
| 1239 | */ |
| 1240 | size_t SdFile::write(const char* str) { |
| 1241 | return write(str, strlen(str)); |
| 1242 | } |
| 1243 | #ifdef __AVR__ |
| 1244 | //------------------------------------------------------------------------------ |
| 1245 | /** |
| 1246 | * Write a PROGMEM string to a file. |
| 1247 | * |
| 1248 | * Use SdFile::writeError to check for errors. |
| 1249 | */ |
| 1250 | void SdFile::write_P(PGM_P str) { |
| 1251 | for (uint8_t c; (c = pgm_read_byte(str)); str++) write(c); |
| 1252 | } |
| 1253 | //------------------------------------------------------------------------------ |
| 1254 | /** |
| 1255 | * Write a PROGMEM string followed by CR/LF to a file. |
| 1256 | * |
| 1257 | * Use SdFile::writeError to check for errors. |
| 1258 | */ |
| 1259 | void SdFile::writeln_P(PGM_P str) { |
| 1260 | write_P(str); |
| 1261 | println(); |
| 1262 | } |
| 1263 | #endif |