[136] | 1 | /* Arduino FAT16 Library
|
---|
| 2 | * Copyright (C) 2008 by William Greiman
|
---|
| 3 | *
|
---|
| 4 | * This file is part of the Arduino FAT16 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 Fat16 Library. If not, see
|
---|
| 18 | * <http://www.gnu.org/licenses/>.
|
---|
| 19 | */
|
---|
| 20 | #include <avr/pgmspace.h>
|
---|
| 21 | #if ARDUINO < 100
|
---|
| 22 | #include <WProgram.h>
|
---|
| 23 | #else // ARDUINO
|
---|
| 24 | #include <Arduino.h>
|
---|
| 25 | #endif // ARDUINO
|
---|
| 26 | #include <Fat16.h>
|
---|
| 27 | //-----------------------------------------------------------------------------
|
---|
| 28 | // volume info
|
---|
| 29 | uint8_t Fat16::volumeInitialized_ = 0; // true if FAT16 volume is valid
|
---|
| 30 | uint8_t Fat16::fatCount_; // number of file allocation tables
|
---|
| 31 | uint8_t Fat16::blocksPerCluster_; // must be power of 2
|
---|
| 32 | uint16_t Fat16::rootDirEntryCount_; // should be 512 for FAT16
|
---|
| 33 | fat_t Fat16::blocksPerFat_; // number of blocks in one FAT
|
---|
| 34 | fat_t Fat16::clusterCount_; // total clusters in volume
|
---|
| 35 | uint32_t Fat16::fatStartBlock_; // start of first FAT
|
---|
| 36 | uint32_t Fat16::rootDirStartBlock_; // start of root dir
|
---|
| 37 | uint32_t Fat16::dataStartBlock_; // start of data clusters
|
---|
| 38 | //------------------------------------------------------------------------------
|
---|
| 39 | // raw block cache
|
---|
| 40 | SdCard *Fat16::rawDev_ = 0; // class for block read and write
|
---|
| 41 | uint32_t Fat16::cacheBlockNumber_ = 0XFFFFFFFF; // init to invalid block number
|
---|
| 42 | cache16_t Fat16::cacheBuffer_; // 512 byte cache for SdCard
|
---|
| 43 | uint8_t Fat16::cacheDirty_ = 0; // cacheFlush() will write block if true
|
---|
| 44 | uint32_t Fat16::cacheMirrorBlock_ = 0; // mirror block for second FAT
|
---|
| 45 | //------------------------------------------------------------------------------
|
---|
| 46 | // callback function for date/time
|
---|
| 47 | void (*Fat16::dateTime_)(uint16_t* date, uint16_t* time) = NULL;
|
---|
| 48 |
|
---|
| 49 | #if ALLOW_DEPRECATED_FUNCTIONS
|
---|
| 50 | void (*Fat16::oldDateTime_)(uint16_t& date, uint16_t& time) = NULL; // NOLINT
|
---|
| 51 | #endif // ALLOW_DEPRECATED_FUNCTIONS
|
---|
| 52 | //------------------------------------------------------------------------------
|
---|
| 53 | // format 8.3 name for directory entry
|
---|
| 54 | static uint8_t make83Name(const char* str, uint8_t* name) {
|
---|
| 55 | uint8_t c;
|
---|
| 56 | uint8_t n = 7; // max index for part before dot
|
---|
| 57 | uint8_t i = 0;
|
---|
| 58 | // blank fill name and extension
|
---|
| 59 | while (i < 11) name[i++] = ' ';
|
---|
| 60 | i = 0;
|
---|
| 61 | while ((c = *str++) != '\0') {
|
---|
| 62 | if (c == '.') {
|
---|
| 63 | if (n == 10) return false; // only one dot allowed
|
---|
| 64 | n = 10; // max index for full 8.3 name
|
---|
| 65 | i = 8; // place for extension
|
---|
| 66 | } else {
|
---|
| 67 | // illegal FAT characters
|
---|
| 68 | PGM_P p = PSTR("|<>^+=?/[];,*\"\\");
|
---|
| 69 | uint8_t b;
|
---|
| 70 | while ((b = pgm_read_byte(p++))) if (b == c) return false;
|
---|
| 71 | // check length and only allow ASCII printable characters
|
---|
| 72 | if (i > n || c < 0X21 || c > 0X7E) return false;
|
---|
| 73 | // only upper case allowed in 8.3 names - convert lower to upper
|
---|
| 74 | name[i++] = c < 'a' || c > 'z' ? c : c + ('A' - 'a');
|
---|
| 75 | }
|
---|
| 76 | }
|
---|
| 77 | // must have a file name, extension is optional
|
---|
| 78 | return name[0] != ' ';
|
---|
| 79 | }
|
---|
| 80 | //==============================================================================
|
---|
| 81 | // Fat16 member functions
|
---|
| 82 | //------------------------------------------------------------------------------
|
---|
| 83 | uint8_t Fat16::addCluster(void) {
|
---|
| 84 | // start search after last cluster of file or at cluster two in FAT
|
---|
| 85 | fat_t freeCluster = curCluster_ ? curCluster_ : 1;
|
---|
| 86 | for (fat_t i = 0; ; i++) {
|
---|
| 87 | // return no free clusters
|
---|
| 88 | if (i >= clusterCount_) return false;
|
---|
| 89 | // Fat has clusterCount + 2 entries
|
---|
| 90 | if (freeCluster > clusterCount_) freeCluster = 1;
|
---|
| 91 | freeCluster++;
|
---|
| 92 | fat_t value;
|
---|
| 93 | if (!fatGet(freeCluster, &value)) return false;
|
---|
| 94 | if (value == 0) break;
|
---|
| 95 | }
|
---|
| 96 | // mark cluster allocated
|
---|
| 97 | if (!fatPut(freeCluster, FAT16EOC)) return false;
|
---|
| 98 |
|
---|
| 99 | if (curCluster_ != 0) {
|
---|
| 100 | // link cluster to chain
|
---|
| 101 | if (!fatPut(curCluster_, freeCluster)) return false;
|
---|
| 102 | } else {
|
---|
| 103 | // first cluster of file so update directory entry
|
---|
| 104 | flags_ |= F_FILE_DIR_DIRTY;
|
---|
| 105 | firstCluster_ = freeCluster;
|
---|
| 106 | }
|
---|
| 107 | curCluster_ = freeCluster;
|
---|
| 108 | return true;
|
---|
| 109 | }
|
---|
| 110 | //------------------------------------------------------------------------------
|
---|
| 111 | //
|
---|
| 112 | dir_t* Fat16::cacheDirEntry(uint16_t index, uint8_t action) {
|
---|
| 113 | if (index >= rootDirEntryCount_) return NULL;
|
---|
| 114 | if (!cacheRawBlock(rootDirStartBlock_ + (index >> 4), action)) return NULL;
|
---|
| 115 | return &cacheBuffer_.dir[index & 0XF];
|
---|
| 116 | }
|
---|
| 117 | //------------------------------------------------------------------------------
|
---|
| 118 | //
|
---|
| 119 | uint8_t Fat16::cacheFlush(void) {
|
---|
| 120 | if (cacheDirty_) {
|
---|
| 121 | if (!rawDev_->writeBlock(cacheBlockNumber_, cacheBuffer_.data)) {
|
---|
| 122 | return false;
|
---|
| 123 | }
|
---|
| 124 | // mirror FAT tables
|
---|
| 125 | if (cacheMirrorBlock_) {
|
---|
| 126 | if (!rawDev_->writeBlock(cacheMirrorBlock_, cacheBuffer_.data)) {
|
---|
| 127 | return false;
|
---|
| 128 | }
|
---|
| 129 | cacheMirrorBlock_ = 0;
|
---|
| 130 | }
|
---|
| 131 | cacheDirty_ = 0;
|
---|
| 132 | }
|
---|
| 133 | return true;
|
---|
| 134 | }
|
---|
| 135 | //------------------------------------------------------------------------------
|
---|
| 136 | //
|
---|
| 137 | uint8_t Fat16::cacheRawBlock(uint32_t blockNumber, uint8_t action) {
|
---|
| 138 | if (cacheBlockNumber_ != blockNumber) {
|
---|
| 139 | if (!cacheFlush()) return false;
|
---|
| 140 | if (!rawDev_->readBlock(blockNumber, cacheBuffer_.data)) return false;
|
---|
| 141 | cacheBlockNumber_ = blockNumber;
|
---|
| 142 | }
|
---|
| 143 | cacheDirty_ |= action;
|
---|
| 144 | return true;
|
---|
| 145 | }
|
---|
| 146 | //------------------------------------------------------------------------------
|
---|
| 147 | /**
|
---|
| 148 | * Close a file and force cached data and directory information
|
---|
| 149 | * to be written to the storage device.
|
---|
| 150 | *
|
---|
| 151 | * \return The value one, true, is returned for success and
|
---|
| 152 | * the value zero, false, is returned for failure.
|
---|
| 153 | * Reasons for failure include no file is open or an I/O error.
|
---|
| 154 | */
|
---|
| 155 | uint8_t Fat16::close(void) {
|
---|
| 156 | if (!sync()) return false;
|
---|
| 157 | flags_ = 0;
|
---|
| 158 | return true;
|
---|
| 159 | }
|
---|
| 160 | //------------------------------------------------------------------------------
|
---|
| 161 | /**
|
---|
| 162 | * Return a files directory entry
|
---|
| 163 | *
|
---|
| 164 | * \param[out] dir Location for return of the files directory entry.
|
---|
| 165 | *
|
---|
| 166 | * \return The value one, true, is returned for success and
|
---|
| 167 | * the value zero, false, is returned for failure.
|
---|
| 168 | */
|
---|
| 169 | uint8_t Fat16::dirEntry(dir_t* dir) {
|
---|
| 170 | if (!sync()) return false;
|
---|
| 171 | dir_t* p = cacheDirEntry(dirEntryIndex_, CACHE_FOR_WRITE);
|
---|
| 172 | if (!p) return false;
|
---|
| 173 | memcpy(dir, p, sizeof(dir_t));
|
---|
| 174 | return true;
|
---|
| 175 | }
|
---|
| 176 | //------------------------------------------------------------------------------
|
---|
| 177 | uint8_t Fat16::fatGet(fat_t cluster, fat_t* value) {
|
---|
| 178 | if (cluster > (clusterCount_ + 1)) return false;
|
---|
| 179 | uint32_t lba = fatStartBlock_ + (cluster >> 8);
|
---|
| 180 | if (lba != cacheBlockNumber_) {
|
---|
| 181 | if (!cacheRawBlock(lba)) return false;
|
---|
| 182 | }
|
---|
| 183 | *value = cacheBuffer_.fat[cluster & 0XFF];
|
---|
| 184 | return true;
|
---|
| 185 | }
|
---|
| 186 | //------------------------------------------------------------------------------
|
---|
| 187 | uint8_t Fat16::fatPut(fat_t cluster, fat_t value) {
|
---|
| 188 | if (cluster < 2) return false;
|
---|
| 189 | if (cluster > (clusterCount_ + 1)) return false;
|
---|
| 190 | uint32_t lba = fatStartBlock_ + (cluster >> 8);
|
---|
| 191 | if (lba != cacheBlockNumber_) {
|
---|
| 192 | if (!cacheRawBlock(lba)) return false;
|
---|
| 193 | }
|
---|
| 194 | cacheBuffer_.fat[cluster & 0XFF] = value;
|
---|
| 195 | cacheSetDirty();
|
---|
| 196 | // mirror second FAT
|
---|
| 197 | if (fatCount_ > 1) cacheMirrorBlock_ = lba + blocksPerFat_;
|
---|
| 198 | return true;
|
---|
| 199 | }
|
---|
| 200 | //------------------------------------------------------------------------------
|
---|
| 201 | // free a cluster chain
|
---|
| 202 | uint8_t Fat16::freeChain(fat_t cluster) {
|
---|
| 203 | while (1) {
|
---|
| 204 | fat_t next;
|
---|
| 205 | if (!fatGet(cluster, &next)) return false;
|
---|
| 206 | if (!fatPut(cluster, 0)) return false;
|
---|
| 207 | if (isEOC(next)) return true;
|
---|
| 208 | cluster = next;
|
---|
| 209 | }
|
---|
| 210 | }
|
---|
| 211 | //------------------------------------------------------------------------------
|
---|
| 212 | /**
|
---|
| 213 | * Initialize a FAT16 volume.
|
---|
| 214 | *
|
---|
| 215 | * \param[in] dev The SdCard where the volume is located.
|
---|
| 216 | *
|
---|
| 217 | * \param[in] part The partition to be used. Legal values for \a part are
|
---|
| 218 | * 1-4 to use the corresponding partition on a device formatted with
|
---|
| 219 | * a MBR, Master Boot Record, or zero if the device is formatted as
|
---|
| 220 | * a super floppy with the FAT boot sector in block zero.
|
---|
| 221 | *
|
---|
| 222 | * \return The value one, true, is returned for success and
|
---|
| 223 | * the value zero, false, is returned for failure. reasons for
|
---|
| 224 | * failure include not finding a valid FAT16 file system in the
|
---|
| 225 | * specified partition, a call to init() after a volume has
|
---|
| 226 | * been successful initialized or an I/O error.
|
---|
| 227 | *
|
---|
| 228 | */
|
---|
| 229 | uint8_t Fat16::init(SdCard* dev, uint8_t part) {
|
---|
| 230 | // error if invalid partition
|
---|
| 231 | if (part > 4) return false;
|
---|
| 232 | rawDev_ = dev;
|
---|
| 233 | uint32_t volumeStartBlock = 0;
|
---|
| 234 | // if part == 0 assume super floppy with FAT16 boot sector in block zero
|
---|
| 235 | // if part > 0 assume mbr volume with partition table
|
---|
| 236 | if (part) {
|
---|
| 237 | if (!cacheRawBlock(volumeStartBlock)) return false;
|
---|
| 238 | volumeStartBlock = cacheBuffer_.mbr.part[part - 1].firstSector;
|
---|
| 239 | }
|
---|
| 240 | if (!cacheRawBlock(volumeStartBlock)) return false;
|
---|
| 241 | // check boot block signature
|
---|
| 242 | if (cacheBuffer_.data[510] != BOOTSIG0 ||
|
---|
| 243 | cacheBuffer_.data[511] != BOOTSIG1) return false;
|
---|
| 244 | bpb_t* bpb = &cacheBuffer_.fbs.bpb;
|
---|
| 245 | fatCount_ = bpb->fatCount;
|
---|
| 246 | blocksPerCluster_ = bpb->sectorsPerCluster;
|
---|
| 247 | blocksPerFat_ = bpb->sectorsPerFat16;
|
---|
| 248 | rootDirEntryCount_ = bpb->rootDirEntryCount;
|
---|
| 249 | fatStartBlock_ = volumeStartBlock + bpb->reservedSectorCount;
|
---|
| 250 | rootDirStartBlock_ = fatStartBlock_ + bpb->fatCount*bpb->sectorsPerFat16;
|
---|
| 251 | dataStartBlock_ = rootDirStartBlock_
|
---|
| 252 | + ((32*bpb->rootDirEntryCount + 511)/512);
|
---|
| 253 | uint32_t totalBlocks = bpb->totalSectors16 ?
|
---|
| 254 | bpb->totalSectors16 : bpb->totalSectors32;
|
---|
| 255 | clusterCount_ = (totalBlocks - (dataStartBlock_ - volumeStartBlock))
|
---|
| 256 | /bpb->sectorsPerCluster;
|
---|
| 257 | // verify valid FAT16 volume
|
---|
| 258 | if (bpb->bytesPerSector != 512 // only allow 512 byte blocks
|
---|
| 259 | || bpb->sectorsPerFat16 == 0 // zero for FAT32
|
---|
| 260 | || clusterCount_ < 4085 // FAT12 if true
|
---|
| 261 | || totalBlocks > 0X800000 // Max size for FAT16 volume
|
---|
| 262 | || bpb->reservedSectorCount == 0 // invalid volume
|
---|
| 263 | || bpb->fatCount == 0 // invalid volume
|
---|
| 264 | || bpb->sectorsPerFat16 < (clusterCount_ >> 8) // invalid volume
|
---|
| 265 | || bpb->sectorsPerCluster == 0 // invalid volume
|
---|
| 266 | // power of 2 test
|
---|
| 267 | || bpb->sectorsPerCluster & (bpb->sectorsPerCluster - 1)) {
|
---|
| 268 | // not a usable FAT16 bpb
|
---|
| 269 | return false;
|
---|
| 270 | }
|
---|
| 271 | volumeInitialized_ = 1;
|
---|
| 272 | return true;
|
---|
| 273 | }
|
---|
| 274 | //------------------------------------------------------------------------------
|
---|
| 275 | /** List directory contents to Serial.
|
---|
| 276 | *
|
---|
| 277 | * \param[in] flags The inclusive OR of
|
---|
| 278 | *
|
---|
| 279 | * LS_DATE - %Print file modification date
|
---|
| 280 | *
|
---|
| 281 | * LS_SIZE - %Print file size.
|
---|
| 282 | */
|
---|
| 283 | void Fat16::ls(uint8_t flags) {
|
---|
| 284 | dir_t d;
|
---|
| 285 | for (uint16_t index = 0; readDir(&d, &index, DIR_ATT_VOLUME_ID); index++) {
|
---|
| 286 | // print file name with possible blank fill
|
---|
| 287 | printDirName(d, flags & (LS_DATE | LS_SIZE) ? 14 : 0);
|
---|
| 288 |
|
---|
| 289 | // print modify date/time if requested
|
---|
| 290 | if (flags & LS_DATE) {
|
---|
| 291 | printFatDate(d.lastWriteDate);
|
---|
| 292 | Serial.write(' ');
|
---|
| 293 | printFatTime(d.lastWriteTime);
|
---|
| 294 | }
|
---|
| 295 |
|
---|
| 296 | // print size if requested
|
---|
| 297 | if (DIR_IS_FILE(&d) && (flags & LS_SIZE)) {
|
---|
| 298 | Serial.write(' ');
|
---|
| 299 | Serial.print(d.fileSize);
|
---|
| 300 | }
|
---|
| 301 | Serial.println();
|
---|
| 302 | }
|
---|
| 303 | }
|
---|
| 304 | //------------------------------------------------------------------------------
|
---|
| 305 | /**
|
---|
| 306 | * Open a file by file name.
|
---|
| 307 | *
|
---|
| 308 | * \note The file must be in the root directory and must have a DOS
|
---|
| 309 | * 8.3 name.
|
---|
| 310 | *
|
---|
| 311 | * \param[in] fileName A valid 8.3 DOS name for a file in the root directory.
|
---|
| 312 | *
|
---|
| 313 | * \param[in] oflag Values for \a oflag are constructed by a bitwise-inclusive
|
---|
| 314 | * OR of flags from the following list
|
---|
| 315 | *
|
---|
| 316 | * O_READ - Open for reading.
|
---|
| 317 | *
|
---|
| 318 | * O_RDONLY - Same as O_READ.
|
---|
| 319 | *
|
---|
| 320 | * O_WRITE - Open for writing.
|
---|
| 321 | *
|
---|
| 322 | * O_WRONLY - Same as O_WRITE.
|
---|
| 323 | *
|
---|
| 324 | * O_RDWR - Open for reading and writing.
|
---|
| 325 | *
|
---|
| 326 | * O_APPEND - If set, the file offset shall be set to the end of the
|
---|
| 327 | * file prior to each write.
|
---|
| 328 | *
|
---|
| 329 | * O_CREAT - If the file exists, this flag has no effect except as noted
|
---|
| 330 | * under O_EXCL below. Otherwise, the file shall be created
|
---|
| 331 | *
|
---|
| 332 | * O_EXCL - If O_CREAT and O_EXCL are set, open() shall fail if the file exists.
|
---|
| 333 | *
|
---|
| 334 | * O_SYNC - Call sync() after each write. This flag should not be used with
|
---|
| 335 | * write(uint8_t), write_P(PGM_P), writeln_P(PGM_P), or the Arduino Print class.
|
---|
| 336 | * These functions do character a time writes so sync() will be called
|
---|
| 337 | * after each byte.
|
---|
| 338 | *
|
---|
| 339 | * O_TRUNC - If the file exists and is a regular file, and the file is
|
---|
| 340 | * successfully opened and is not read only, its length shall be truncated to 0.
|
---|
| 341 | *
|
---|
| 342 | * \return The value one, true, is returned for success and
|
---|
| 343 | * the value zero, false, is returned for failure.
|
---|
| 344 | * Reasons for failure include the FAT volume has not been initialized,
|
---|
| 345 | * a file is already open, \a fileName is invalid, the file does not exist,
|
---|
| 346 | * is a directory, or can't be opened in the access mode specified by oflag.
|
---|
| 347 | */
|
---|
| 348 | uint8_t Fat16::open(const char* fileName, uint8_t oflag) {
|
---|
| 349 | uint8_t dname[11]; // name formated for dir entry
|
---|
| 350 | int16_t empty = -1; // index of empty slot
|
---|
| 351 | dir_t* p; // pointer to cached dir entry
|
---|
| 352 |
|
---|
| 353 | if (!volumeInitialized_ || isOpen()) return false;
|
---|
| 354 |
|
---|
| 355 | // error if invalid name
|
---|
| 356 | if (!make83Name(fileName, dname)) return false;
|
---|
| 357 |
|
---|
| 358 | for (uint16_t index = 0; index < rootDirEntryCount_; index++) {
|
---|
| 359 | if (!(p = cacheDirEntry(index))) return false;
|
---|
| 360 | if (p->name[0] == DIR_NAME_FREE || p->name[0] == DIR_NAME_DELETED) {
|
---|
| 361 | // remember first empty slot
|
---|
| 362 | if (empty < 0) empty = index;
|
---|
| 363 | // done if no entries follow
|
---|
| 364 | if (p->name[0] == DIR_NAME_FREE) break;
|
---|
| 365 | } else if (!memcmp(dname, p->name, 11)) {
|
---|
| 366 | // don't open existing file if O_CREAT and O_EXCL
|
---|
| 367 | if ((oflag & (O_CREAT | O_EXCL)) == (O_CREAT | O_EXCL)) return false;
|
---|
| 368 |
|
---|
| 369 | // open existing file
|
---|
| 370 | return open(index, oflag);
|
---|
| 371 | }
|
---|
| 372 | }
|
---|
| 373 | // error if directory is full
|
---|
| 374 | if (empty < 0) return false;
|
---|
| 375 |
|
---|
| 376 | // only create file if O_CREAT and O_WRITE
|
---|
| 377 | if ((oflag & (O_CREAT | O_WRITE)) != (O_CREAT | O_WRITE)) return false;
|
---|
| 378 |
|
---|
| 379 | if (!(p = cacheDirEntry(empty, CACHE_FOR_WRITE))) return false;
|
---|
| 380 |
|
---|
| 381 | // initialize as empty file
|
---|
| 382 | memset(p, 0, sizeof(dir_t));
|
---|
| 383 | memcpy(p->name, dname, 11);
|
---|
| 384 |
|
---|
| 385 | // set timestamps
|
---|
| 386 | if (dateTime_) {
|
---|
| 387 | // call user function
|
---|
| 388 | dateTime_(&p->creationDate, &p->creationTime);
|
---|
| 389 | } else {
|
---|
| 390 | // use default date/time
|
---|
| 391 | p->creationDate = FAT_DEFAULT_DATE;
|
---|
| 392 | p->creationTime = FAT_DEFAULT_TIME;
|
---|
| 393 | }
|
---|
| 394 | p->lastAccessDate = p->creationDate;
|
---|
| 395 | p->lastWriteDate = p->creationDate;
|
---|
| 396 | p->lastWriteTime = p->creationTime;
|
---|
| 397 |
|
---|
| 398 | // insure created directory entry will be written to storage device
|
---|
| 399 | if (!cacheFlush()) return false;
|
---|
| 400 |
|
---|
| 401 | // open entry
|
---|
| 402 | return open(empty, oflag);
|
---|
| 403 | }
|
---|
| 404 | //------------------------------------------------------------------------------
|
---|
| 405 | /**
|
---|
| 406 | * Open a file by file index.
|
---|
| 407 | *
|
---|
| 408 | * \param[in] index The root directory index of the file to be opened. See \link
|
---|
| 409 | * Fat16::readDir() readDir()\endlink.
|
---|
| 410 | *
|
---|
| 411 | * \param[in] oflag See \link Fat16::open(const char*, uint8_t)\endlink.
|
---|
| 412 | *
|
---|
| 413 | * \return The value one, true, is returned for success and
|
---|
| 414 | * the value zero, false, is returned for failure.
|
---|
| 415 | * Reasons for failure include the FAT volume has not been initialized,
|
---|
| 416 | * a file is already open, \a index is invalid or is not the index of a
|
---|
| 417 | * file or the file cannot be opened in the access mode specified by oflag.
|
---|
| 418 | */
|
---|
| 419 | uint8_t Fat16::open(uint16_t index, uint8_t oflag) {
|
---|
| 420 | if (!volumeInitialized_ || isOpen()) return false;
|
---|
| 421 | if ((oflag & O_TRUNC) && !(oflag & O_WRITE)) return false;
|
---|
| 422 | dir_t* d = cacheDirEntry(index);
|
---|
| 423 | // if bad file index or I/O error
|
---|
| 424 | if (!d) return false;
|
---|
| 425 |
|
---|
| 426 | // error if unused entry
|
---|
| 427 | if (d->name[0] == DIR_NAME_FREE || d->name[0] == DIR_NAME_DELETED) {
|
---|
| 428 | return false;
|
---|
| 429 | }
|
---|
| 430 | // error if long name, volume label or subdirectory
|
---|
| 431 | if ((d->attributes & (DIR_ATT_VOLUME_ID | DIR_ATT_DIRECTORY)) != 0) {
|
---|
| 432 | return false;
|
---|
| 433 | }
|
---|
| 434 | // don't allow write or truncate if read-only
|
---|
| 435 | if (d->attributes & DIR_ATT_READ_ONLY) {
|
---|
| 436 | if (oflag & (O_WRITE | O_TRUNC)) return false;
|
---|
| 437 | }
|
---|
| 438 |
|
---|
| 439 | curCluster_ = 0;
|
---|
| 440 | curPosition_ = 0;
|
---|
| 441 | dirEntryIndex_ = index;
|
---|
| 442 | fileSize_ = d->fileSize;
|
---|
| 443 | firstCluster_ = d->firstClusterLow;
|
---|
| 444 | flags_ = oflag & (O_ACCMODE | O_SYNC | O_APPEND);
|
---|
| 445 |
|
---|
| 446 | if (oflag & O_TRUNC ) return truncate(0);
|
---|
| 447 | return true;
|
---|
| 448 | }
|
---|
| 449 | //------------------------------------------------------------------------------
|
---|
| 450 | /** %Print the name field of a directory entry in 8.3 format to Serial.
|
---|
| 451 | *
|
---|
| 452 | * \param[in] dir The directory structure containing the name.
|
---|
| 453 | * \param[in] width Blank fill name if length is less than \a width.
|
---|
| 454 | */
|
---|
| 455 | void Fat16::printDirName(const dir_t& dir, uint8_t width) {
|
---|
| 456 | uint8_t w = 0;
|
---|
| 457 | for (uint8_t i = 0; i < 11; i++) {
|
---|
| 458 | if (dir.name[i] == ' ') continue;
|
---|
| 459 | if (i == 8) {
|
---|
| 460 | Serial.write('.');
|
---|
| 461 | w++;
|
---|
| 462 | }
|
---|
| 463 | Serial.write(dir.name[i]);
|
---|
| 464 | w++;
|
---|
| 465 | }
|
---|
| 466 | if (DIR_IS_SUBDIR(&dir)) {
|
---|
| 467 | Serial.write('/');
|
---|
| 468 | w++;
|
---|
| 469 | }
|
---|
| 470 | while (w < width) {
|
---|
| 471 | Serial.write(' ');
|
---|
| 472 | w++;
|
---|
| 473 | }
|
---|
| 474 | }
|
---|
| 475 | //------------------------------------------------------------------------------
|
---|
| 476 | /** %Print a directory date field to Serial.
|
---|
| 477 | *
|
---|
| 478 | * Format is yyyy-mm-dd.
|
---|
| 479 | *
|
---|
| 480 | * \param[in] fatDate The date field from a directory entry.
|
---|
| 481 | */
|
---|
| 482 | void Fat16::printFatDate(uint16_t fatDate) {
|
---|
| 483 | Serial.print(FAT_YEAR(fatDate));
|
---|
| 484 | Serial.write('-');
|
---|
| 485 | printTwoDigits(FAT_MONTH(fatDate));
|
---|
| 486 | Serial.write('-');
|
---|
| 487 | printTwoDigits(FAT_DAY(fatDate));
|
---|
| 488 | }
|
---|
| 489 | //------------------------------------------------------------------------------
|
---|
| 490 | /** %Print a directory time field to Serial.
|
---|
| 491 | *
|
---|
| 492 | * Format is hh:mm:ss.
|
---|
| 493 | *
|
---|
| 494 | * \param[in] fatTime The time field from a directory entry.
|
---|
| 495 | */
|
---|
| 496 | void Fat16::printFatTime(uint16_t fatTime) {
|
---|
| 497 | printTwoDigits(FAT_HOUR(fatTime));
|
---|
| 498 | Serial.write(':');
|
---|
| 499 | printTwoDigits(FAT_MINUTE(fatTime));
|
---|
| 500 | Serial.write(':');
|
---|
| 501 | printTwoDigits(FAT_SECOND(fatTime));
|
---|
| 502 | }
|
---|
| 503 |
|
---|
| 504 | //------------------------------------------------------------------------------
|
---|
| 505 | /** %Print a value as two digits to Serial.
|
---|
| 506 | *
|
---|
| 507 | * \param[in] v Value to be printed, 0 <= \a v <= 99
|
---|
| 508 | */
|
---|
| 509 | void Fat16::printTwoDigits(uint8_t v) {
|
---|
| 510 | char str[3];
|
---|
| 511 | str[0] = '0' + v/10;
|
---|
| 512 | str[1] = '0' + v % 10;
|
---|
| 513 | str[2] = 0;
|
---|
| 514 | Serial.print(str);
|
---|
| 515 | }
|
---|
| 516 | //------------------------------------------------------------------------------
|
---|
| 517 | /**
|
---|
| 518 | * Read the next byte from a file.
|
---|
| 519 | *
|
---|
| 520 | * \return For success read returns the next byte in the file as an int.
|
---|
| 521 | * If an error occurs or end of file is reached -1 is returned.
|
---|
| 522 | */
|
---|
| 523 | int16_t Fat16::read(void) {
|
---|
| 524 | uint8_t b;
|
---|
| 525 | return read(&b, 1) == 1 ? b : -1;
|
---|
| 526 | }
|
---|
| 527 | //------------------------------------------------------------------------------
|
---|
| 528 | /**
|
---|
| 529 | * Read data from a file at starting at the current file position.
|
---|
| 530 | *
|
---|
| 531 | * \param[out] buf Pointer to the location that will receive the data.
|
---|
| 532 | *
|
---|
| 533 | * \param[in] nbyte Maximum number of bytes to read.
|
---|
| 534 | *
|
---|
| 535 | * \return For success read returns the number of bytes read.
|
---|
| 536 | * A value less than \a nbyte, including zero, may be returned
|
---|
| 537 | * if end of file is reached.
|
---|
| 538 | * If an error occurs, read returns -1. Possible errors include
|
---|
| 539 | * read called before a file has been opened, the file has not been opened in
|
---|
| 540 | * read mode, a corrupt file system, or an I/O error.
|
---|
| 541 | */
|
---|
| 542 | int16_t Fat16::read(void* buf, uint16_t nbyte) {
|
---|
| 543 | // convert void pointer to uin8_t pointer
|
---|
| 544 | uint8_t* dst = reinterpret_cast<uint8_t*>(buf);
|
---|
| 545 |
|
---|
| 546 | // error if not open for read
|
---|
| 547 | if (!(flags_ & O_READ)) return -1;
|
---|
| 548 |
|
---|
| 549 | // don't read beyond end of file
|
---|
| 550 | if ((curPosition_ + nbyte) > fileSize_) nbyte = fileSize_ - curPosition_;
|
---|
| 551 |
|
---|
| 552 | // bytes left to read in loop
|
---|
| 553 | uint16_t nToRead = nbyte;
|
---|
| 554 | while (nToRead > 0) {
|
---|
| 555 | uint8_t blkOfCluster = blockOfCluster(curPosition_);
|
---|
| 556 | uint16_t blockOffset = cacheDataOffset(curPosition_);
|
---|
| 557 | if (blkOfCluster == 0 && blockOffset == 0) {
|
---|
| 558 | // start next cluster
|
---|
| 559 | if (curCluster_ == 0) {
|
---|
| 560 | curCluster_ = firstCluster_;
|
---|
| 561 | } else {
|
---|
| 562 | if (!fatGet(curCluster_, &curCluster_)) return -1;
|
---|
| 563 | }
|
---|
| 564 | // return error if bad cluster chain
|
---|
| 565 | if (curCluster_ < 2 || isEOC(curCluster_)) return -1;
|
---|
| 566 | }
|
---|
| 567 | // cache data block
|
---|
| 568 | if (!cacheRawBlock(dataBlockLba(curCluster_, blkOfCluster))) return -1;
|
---|
| 569 |
|
---|
| 570 | // location of data in cache
|
---|
| 571 | uint8_t* src = cacheBuffer_.data + blockOffset;
|
---|
| 572 |
|
---|
| 573 | // max number of byte available in block
|
---|
| 574 | uint16_t n = 512 - blockOffset;
|
---|
| 575 |
|
---|
| 576 | // lesser of available and amount to read
|
---|
| 577 | if (n > nToRead) n = nToRead;
|
---|
| 578 |
|
---|
| 579 | // copy data to caller
|
---|
| 580 | memcpy(dst, src, n);
|
---|
| 581 |
|
---|
| 582 | curPosition_ += n;
|
---|
| 583 | dst += n;
|
---|
| 584 | nToRead -= n;
|
---|
| 585 | }
|
---|
| 586 | return nbyte;
|
---|
| 587 | }
|
---|
| 588 | //------------------------------------------------------------------------------
|
---|
| 589 | /**
|
---|
| 590 | * Read the next short, 8.3, directory entry.
|
---|
| 591 | *
|
---|
| 592 | * Unused entries and entries for long names are skipped.
|
---|
| 593 | *
|
---|
| 594 | * \param[out] dir Location that will receive the entry.
|
---|
| 595 | *
|
---|
| 596 | * \param[in,out] index The search starts at \a index and \a index is
|
---|
| 597 | * updated with the root directory index of the found directory entry.
|
---|
| 598 | * If the entry is a file, it may be opened by calling
|
---|
| 599 | * \link Fat16::open(uint16_t, uint8_t) \endlink.
|
---|
| 600 | *
|
---|
| 601 | * \param[in] skip Skip entries that have these attributes. If \a skip
|
---|
| 602 | * is not specified, the default is to skip the volume label and directories.
|
---|
| 603 | *
|
---|
| 604 | * \return The value one, true, is returned for success and the value zero,
|
---|
| 605 | * false, is returned if an error occurs or the end of the root directory is
|
---|
| 606 | * reached. On success, \a entry is set to the index of the found directory
|
---|
| 607 | * entry.
|
---|
| 608 | */
|
---|
| 609 | uint8_t Fat16::readDir(dir_t* dir, uint16_t* index, uint8_t skip) {
|
---|
| 610 | dir_t* p;
|
---|
| 611 | for (uint16_t i = *index; ; i++) {
|
---|
| 612 | if (i >= rootDirEntryCount_) return false;
|
---|
| 613 | if (!(p = cacheDirEntry(i))) return false;
|
---|
| 614 |
|
---|
| 615 | // done if beyond last used entry
|
---|
| 616 | if (p->name[0] == DIR_NAME_FREE) return false;
|
---|
| 617 |
|
---|
| 618 | // skip deleted entry
|
---|
| 619 | if (p->name[0] == DIR_NAME_DELETED) continue;
|
---|
| 620 |
|
---|
| 621 | // skip long names
|
---|
| 622 | if ((p->attributes & DIR_ATT_LONG_NAME_MASK) == DIR_ATT_LONG_NAME) continue;
|
---|
| 623 |
|
---|
| 624 | // skip if attribute match
|
---|
| 625 | if (p->attributes & skip) continue;
|
---|
| 626 |
|
---|
| 627 | // return found index
|
---|
| 628 | *index = i;
|
---|
| 629 | break;
|
---|
| 630 | }
|
---|
| 631 | memcpy(dir, p, sizeof(dir_t));
|
---|
| 632 | return true;
|
---|
| 633 | }
|
---|
| 634 | //------------------------------------------------------------------------------
|
---|
| 635 | /**
|
---|
| 636 | * Remove a file. The directory entry and all data for the file are deleted.
|
---|
| 637 | *
|
---|
| 638 | * \note This function should not be used to delete the 8.3 version of a
|
---|
| 639 | * file that has a long name. For example if a file has the long name
|
---|
| 640 | * "New Text Document.txt" you should not delete the 8.3 name "NEWTEX~1.TXT".
|
---|
| 641 | *
|
---|
| 642 | * \return The value one, true, is returned for success and
|
---|
| 643 | * the value zero, false, is returned for failure.
|
---|
| 644 | * Reasons for failure include the file is not open for write
|
---|
| 645 | * or an I/O error occurred.
|
---|
| 646 | */
|
---|
| 647 | uint8_t Fat16::remove(void) {
|
---|
| 648 | // error if file is not open for write
|
---|
| 649 | if (!(flags_ & O_WRITE)) return false;
|
---|
| 650 | if (firstCluster_) {
|
---|
| 651 | if (!freeChain(firstCluster_)) return false;
|
---|
| 652 | }
|
---|
| 653 | dir_t* d = cacheDirEntry(dirEntryIndex_, CACHE_FOR_WRITE);
|
---|
| 654 | if (!d) return false;
|
---|
| 655 | d->name[0] = DIR_NAME_DELETED;
|
---|
| 656 | flags_ = 0;
|
---|
| 657 | return cacheFlush();
|
---|
| 658 | }
|
---|
| 659 | //------------------------------------------------------------------------------
|
---|
| 660 | /**
|
---|
| 661 | * Remove a file.
|
---|
| 662 | *
|
---|
| 663 | * The directory entry and all data for the file are deleted.
|
---|
| 664 | *
|
---|
| 665 | * \param[in] fileName The name of the file to be removed.
|
---|
| 666 | *
|
---|
| 667 | * \note This function should not be used to delete the 8.3 version of a
|
---|
| 668 | * file that has a long name. For example if a file has the long name
|
---|
| 669 | * "New Text Document.txt" you should not delete the 8.3 name "NEWTEX~1.TXT".
|
---|
| 670 | *
|
---|
| 671 | * \return The value one, true, is returned for success and
|
---|
| 672 | * the value zero, false, is returned for failure.
|
---|
| 673 | * Reasons for failure include the file is read only, \a fileName is not found
|
---|
| 674 | * or an I/O error occurred.
|
---|
| 675 | */
|
---|
| 676 | uint8_t Fat16::remove(const char* fileName) {
|
---|
| 677 | Fat16 file;
|
---|
| 678 | if (!file.open(fileName, O_WRITE)) return false;
|
---|
| 679 | return file.remove();
|
---|
| 680 | }
|
---|
| 681 | //------------------------------------------------------------------------------
|
---|
| 682 | /**
|
---|
| 683 | * Sets the file's read/write position.
|
---|
| 684 | *
|
---|
| 685 | * \param[in] pos The new position in bytes from the beginning of the file.
|
---|
| 686 | *
|
---|
| 687 | * \return The value one, true, is returned for success and
|
---|
| 688 | * the value zero, false, is returned for failure.
|
---|
| 689 | */
|
---|
| 690 | uint8_t Fat16::seekSet(uint32_t pos) {
|
---|
| 691 | // error if file not open or seek past end of file
|
---|
| 692 | if (!isOpen() || pos > fileSize_) return false;
|
---|
| 693 | if (pos == 0) {
|
---|
| 694 | // set position to start of file
|
---|
| 695 | curCluster_ = 0;
|
---|
| 696 | curPosition_ = 0;
|
---|
| 697 | return true;
|
---|
| 698 | }
|
---|
| 699 | fat_t n = ((pos - 1) >> 9)/blocksPerCluster_;
|
---|
| 700 | if (pos < curPosition_ || curPosition_ == 0) {
|
---|
| 701 | // must follow chain from first cluster
|
---|
| 702 | curCluster_ = firstCluster_;
|
---|
| 703 | } else {
|
---|
| 704 | // advance from curPosition
|
---|
| 705 | n -= ((curPosition_ - 1) >> 9)/blocksPerCluster_;
|
---|
| 706 | }
|
---|
| 707 | while (n--) {
|
---|
| 708 | if (!fatGet(curCluster_, &curCluster_)) return false;
|
---|
| 709 | }
|
---|
| 710 | curPosition_ = pos;
|
---|
| 711 | return true;
|
---|
| 712 | }
|
---|
| 713 | //------------------------------------------------------------------------------
|
---|
| 714 | /**
|
---|
| 715 | * The sync() call causes all modified data and directory fields
|
---|
| 716 | * to be written to the storage device.
|
---|
| 717 | *
|
---|
| 718 | * \return The value one, true, is returned for success and
|
---|
| 719 | * the value zero, false, is returned for failure.
|
---|
| 720 | * Reasons for failure include a call to sync() before a file has been
|
---|
| 721 | * opened or an I/O error.
|
---|
| 722 | */
|
---|
| 723 | uint8_t Fat16::sync(void) {
|
---|
| 724 | if (flags_ & F_FILE_DIR_DIRTY) {
|
---|
| 725 | // cache directory entry
|
---|
| 726 | dir_t* d = cacheDirEntry(dirEntryIndex_, CACHE_FOR_WRITE);
|
---|
| 727 | if (!d) return false;
|
---|
| 728 |
|
---|
| 729 | // update file size and first cluster
|
---|
| 730 | d->fileSize = fileSize_;
|
---|
| 731 | d->firstClusterLow = firstCluster_;
|
---|
| 732 |
|
---|
| 733 | // set modify time if user supplied a callback date/time function
|
---|
| 734 | if (dateTime_) {
|
---|
| 735 | dateTime_(&d->lastWriteDate, &d->lastWriteTime);
|
---|
| 736 | d->lastAccessDate = d->lastWriteDate;
|
---|
| 737 | }
|
---|
| 738 | flags_ &= ~F_FILE_DIR_DIRTY;
|
---|
| 739 | }
|
---|
| 740 | return cacheFlush();
|
---|
| 741 | }
|
---|
| 742 | //------------------------------------------------------------------------------
|
---|
| 743 | /**
|
---|
| 744 | * The timestamp() call sets a file's timestamps in its directory entry.
|
---|
| 745 | *
|
---|
| 746 | * \param[in] flags Values for \a flags are constructed by a bitwise-inclusive
|
---|
| 747 | * OR of flags from the following list
|
---|
| 748 | *
|
---|
| 749 | * T_ACCESS - Set the file's last access date.
|
---|
| 750 | *
|
---|
| 751 | * T_CREATE - Set the file's creation date and time.
|
---|
| 752 | *
|
---|
| 753 | * T_WRITE - Set the file's last write/modification date and time.
|
---|
| 754 | *
|
---|
| 755 | * \param[in] year Valid range 1980 - 2107 inclusive.
|
---|
| 756 | *
|
---|
| 757 | * \param[in] month Valid range 1 - 12 inclusive.
|
---|
| 758 | *
|
---|
| 759 | * \param[in] day Valid range 1 - 31 inclusive.
|
---|
| 760 | *
|
---|
| 761 | * \param[in] hour Valid range 0 - 23 inclusive.
|
---|
| 762 | *
|
---|
| 763 | * \param[in] minute Valid range 0 - 59 inclusive.
|
---|
| 764 | *
|
---|
| 765 | * \param[in] second Valid range 0 - 59 inclusive
|
---|
| 766 | *
|
---|
| 767 | * \note It is possible to set an invalid date since there is no check for
|
---|
| 768 | * the number of days in a month.
|
---|
| 769 | *
|
---|
| 770 | * \return The value one, true, is returned for success and
|
---|
| 771 | * the value zero, false, is returned for failure.
|
---|
| 772 | */
|
---|
| 773 | uint8_t Fat16::timestamp(uint8_t flags, uint16_t year, uint8_t month,
|
---|
| 774 | uint8_t day, uint8_t hour, uint8_t minute, uint8_t second) {
|
---|
| 775 | if (!isOpen()
|
---|
| 776 | || year < 1980
|
---|
| 777 | || year > 2107
|
---|
| 778 | || month < 1
|
---|
| 779 | || month > 12
|
---|
| 780 | || day < 1
|
---|
| 781 | || day > 31
|
---|
| 782 | || hour > 23
|
---|
| 783 | || minute > 59
|
---|
| 784 | || second > 59) {
|
---|
| 785 | return false;
|
---|
| 786 | }
|
---|
| 787 | dir_t* d = cacheDirEntry(dirEntryIndex_, CACHE_FOR_WRITE);
|
---|
| 788 | if (!d) return false;
|
---|
| 789 | uint16_t dirDate = FAT_DATE(year, month, day);
|
---|
| 790 | uint16_t dirTime = FAT_TIME(hour, minute, second);
|
---|
| 791 | if (flags & T_ACCESS) {
|
---|
| 792 | d->lastAccessDate = dirDate;
|
---|
| 793 | }
|
---|
| 794 | if (flags & T_CREATE) {
|
---|
| 795 | d->creationDate = dirDate;
|
---|
| 796 | d->creationTime = dirTime;
|
---|
| 797 | // seems to be units of 1/100 second not 1/10 as Microsoft standard states
|
---|
| 798 | d->creationTimeTenths = second & 1 ? 100 : 0;
|
---|
| 799 | }
|
---|
| 800 | if (flags & T_WRITE) {
|
---|
| 801 | d->lastWriteDate = dirDate;
|
---|
| 802 | d->lastWriteTime = dirTime;
|
---|
| 803 | }
|
---|
| 804 | cacheSetDirty();
|
---|
| 805 | return sync();
|
---|
| 806 | }
|
---|
| 807 | //------------------------------------------------------------------------------
|
---|
| 808 | /**
|
---|
| 809 | * Truncate a file to a specified length. The current file position
|
---|
| 810 | * will be maintained if it is less than or equal to \a length otherwise
|
---|
| 811 | * it will be set to end of file.
|
---|
| 812 | *
|
---|
| 813 | * \param[in] length The desired length for the file.
|
---|
| 814 | *
|
---|
| 815 | * \return The value one, true, is returned for success and
|
---|
| 816 | * the value zero, false, is returned for failure.
|
---|
| 817 | * Reasons for failure include file is read only, file is a directory,
|
---|
| 818 | * \a length is greater than the current file size or an I/O error occurs.
|
---|
| 819 | */
|
---|
| 820 | uint8_t Fat16::truncate(uint32_t length) {
|
---|
| 821 | // error if file is not open for write
|
---|
| 822 | if (!(flags_ & O_WRITE)) return false;
|
---|
| 823 |
|
---|
| 824 | if (length > fileSize_) return false;
|
---|
| 825 |
|
---|
| 826 | // fileSize and length are zero - nothing to do
|
---|
| 827 | if (fileSize_ == 0) return true;
|
---|
| 828 | uint32_t newPos = curPosition_ > length ? length : curPosition_;
|
---|
| 829 | if (length == 0) {
|
---|
| 830 | // free all clusters
|
---|
| 831 | if (!freeChain(firstCluster_)) return false;
|
---|
| 832 | curCluster_ = firstCluster_ = 0;
|
---|
| 833 | } else {
|
---|
| 834 | fat_t toFree;
|
---|
| 835 | if (!seekSet(length)) return false;
|
---|
| 836 | if (!fatGet(curCluster_, &toFree)) return false;
|
---|
| 837 | if (!isEOC(toFree)) {
|
---|
| 838 | // free extra clusters
|
---|
| 839 | if (!fatPut(curCluster_, FAT16EOC)) return false;
|
---|
| 840 | if (!freeChain(toFree)) return false;
|
---|
| 841 | }
|
---|
| 842 | }
|
---|
| 843 | fileSize_ = length;
|
---|
| 844 | flags_ |= F_FILE_DIR_DIRTY;
|
---|
| 845 | if (!sync()) return false;
|
---|
| 846 | return seekSet(newPos);
|
---|
| 847 | }
|
---|
| 848 | //------------------------------------------------------------------------------
|
---|
| 849 | /**
|
---|
| 850 | * Write data at the current position of an open file.
|
---|
| 851 | *
|
---|
| 852 | * \note Data is moved to the cache but may not be written to the
|
---|
| 853 | * storage device until sync() is called.
|
---|
| 854 | *
|
---|
| 855 | * \param[in] buf Pointer to the location of the data to be written.
|
---|
| 856 | *
|
---|
| 857 | * \param[in] nbyte Number of bytes to write.
|
---|
| 858 | *
|
---|
| 859 | * \return For success write() returns the number of bytes written, always
|
---|
| 860 | * \a nbyte. If an error occurs, write() returns -1. Possible errors include
|
---|
| 861 | * write() is called before a file has been opened, the file has not been opened
|
---|
| 862 | * for write, device is full, a corrupt file system or an I/O error.
|
---|
| 863 | *
|
---|
| 864 | */
|
---|
| 865 | int16_t Fat16::write(const void* buf, uint16_t nbyte) {
|
---|
| 866 | uint16_t nToWrite = nbyte;
|
---|
| 867 | const uint8_t* src = reinterpret_cast<const uint8_t*>(buf);
|
---|
| 868 |
|
---|
| 869 | // error if file is not open for write
|
---|
| 870 | if (!(flags_ & O_WRITE)) goto writeErrorReturn;
|
---|
| 871 |
|
---|
| 872 | // go to end of file if O_APPEND
|
---|
| 873 | if ((flags_ & O_APPEND) && curPosition_ != fileSize_) {
|
---|
| 874 | if (!seekEnd()) goto writeErrorReturn;
|
---|
| 875 | }
|
---|
| 876 | while (nToWrite > 0) {
|
---|
| 877 | uint8_t blkOfCluster = blockOfCluster(curPosition_);
|
---|
| 878 | uint16_t blockOffset = cacheDataOffset(curPosition_);
|
---|
| 879 | if (blkOfCluster == 0 && blockOffset == 0) {
|
---|
| 880 | // start of new cluster
|
---|
| 881 | if (curCluster_ == 0) {
|
---|
| 882 | if (firstCluster_ == 0) {
|
---|
| 883 | // allocate first cluster of file
|
---|
| 884 | if (!addCluster()) goto writeErrorReturn;
|
---|
| 885 | } else {
|
---|
| 886 | curCluster_ = firstCluster_;
|
---|
| 887 | }
|
---|
| 888 | } else {
|
---|
| 889 | fat_t next;
|
---|
| 890 | if (!fatGet(curCluster_, &next)) goto writeErrorReturn;
|
---|
| 891 | if (isEOC(next)) {
|
---|
| 892 | // add cluster if at end of chain
|
---|
| 893 | if (!addCluster()) goto writeErrorReturn;
|
---|
| 894 | } else {
|
---|
| 895 | curCluster_ = next;
|
---|
| 896 | }
|
---|
| 897 | }
|
---|
| 898 | }
|
---|
| 899 | uint32_t lba = dataBlockLba(curCluster_, blkOfCluster);
|
---|
| 900 | if (blockOffset == 0 && curPosition_ >= fileSize_) {
|
---|
| 901 | // start of new block don't need to read into cache
|
---|
| 902 | if (!cacheFlush()) goto writeErrorReturn;
|
---|
| 903 | cacheBlockNumber_ = lba;
|
---|
| 904 | cacheSetDirty();
|
---|
| 905 | } else {
|
---|
| 906 | // rewrite part of block
|
---|
| 907 | if (!cacheRawBlock(lba, CACHE_FOR_WRITE)) return -1;
|
---|
| 908 | }
|
---|
| 909 | uint8_t* dst = cacheBuffer_.data + blockOffset;
|
---|
| 910 |
|
---|
| 911 | // max space in block
|
---|
| 912 | uint16_t n = 512 - blockOffset;
|
---|
| 913 |
|
---|
| 914 | // lesser of space and amount to write
|
---|
| 915 | if (n > nToWrite) n = nToWrite;
|
---|
| 916 |
|
---|
| 917 | // copy data to cache
|
---|
| 918 | memcpy(dst, src, n);
|
---|
| 919 |
|
---|
| 920 | curPosition_ += n;
|
---|
| 921 | nToWrite -= n;
|
---|
| 922 | src += n;
|
---|
| 923 | }
|
---|
| 924 | if (curPosition_ > fileSize_) {
|
---|
| 925 | // update fileSize and insure sync will update dir entry
|
---|
| 926 | fileSize_ = curPosition_;
|
---|
| 927 | flags_ |= F_FILE_DIR_DIRTY;
|
---|
| 928 | } else if (dateTime_ && nbyte) {
|
---|
| 929 | // insure sync will update modified date and time
|
---|
| 930 | flags_ |= F_FILE_DIR_DIRTY;
|
---|
| 931 | }
|
---|
| 932 |
|
---|
| 933 | if (flags_ & O_SYNC) {
|
---|
| 934 | if (!sync()) goto writeErrorReturn;
|
---|
| 935 | }
|
---|
| 936 | return nbyte;
|
---|
| 937 |
|
---|
| 938 | writeErrorReturn:
|
---|
| 939 | writeError = true;
|
---|
| 940 | return -1;
|
---|
| 941 | }
|
---|
| 942 | //------------------------------------------------------------------------------
|
---|
| 943 | /**
|
---|
| 944 | * Write a byte to a file. Required by the Arduino Print class.
|
---|
| 945 | *
|
---|
| 946 | * Use Fat16::writeError to check for errors.
|
---|
| 947 | */
|
---|
| 948 | #if ARDUINO < 100
|
---|
| 949 | void Fat16::write(uint8_t b) {
|
---|
| 950 | write(&b, 1);
|
---|
| 951 | }
|
---|
| 952 | #else // ARDUINO < 100
|
---|
| 953 | size_t Fat16::write(uint8_t b) {
|
---|
| 954 | return write(&b, 1) == 1 ? 1 : 0;
|
---|
| 955 | }
|
---|
| 956 | #endif // ARDUINO < 100
|
---|
| 957 | //------------------------------------------------------------------------------
|
---|
| 958 | /**
|
---|
| 959 | * Write a string to a file. Used by the Arduino Print class.
|
---|
| 960 | *
|
---|
| 961 | * Use Fat16::writeError to check for errors.
|
---|
| 962 | */
|
---|
| 963 | #if ARDUINO < 100
|
---|
| 964 | void Fat16::write(const char* str) {
|
---|
| 965 | write(str, strlen(str));
|
---|
| 966 | }
|
---|
| 967 | #else // ARDUINO < 100
|
---|
| 968 | int16_t Fat16::write(const char* str) {
|
---|
| 969 | return write(str, strlen(str));
|
---|
| 970 | }
|
---|
| 971 | #endif // ARDUINO < 100
|
---|
| 972 | //------------------------------------------------------------------------------
|
---|
| 973 | /**
|
---|
| 974 | * Write a PROGMEM string to a file.
|
---|
| 975 | *
|
---|
| 976 | * Use Fat16::writeError to check for errors.
|
---|
| 977 | */
|
---|
| 978 | void Fat16::write_P(PGM_P str) {
|
---|
| 979 | for (uint8_t c; (c = pgm_read_byte(str)); str++) write(c);
|
---|
| 980 | }
|
---|
| 981 | //------------------------------------------------------------------------------
|
---|
| 982 | /**
|
---|
| 983 | * Write a PROGMEM string followed by CR/LF to a file.
|
---|
| 984 | *
|
---|
| 985 | * Use Fat16::writeError to check for errors.
|
---|
| 986 | */
|
---|
| 987 | void Fat16::writeln_P(PGM_P str) {
|
---|
| 988 | write_P(str);
|
---|
| 989 | println();
|
---|
| 990 | }
|
---|