Marlin_Firmware/Marlin/src/sd/SdBaseFile.cpp

1814 lines
52 KiB
C++
Raw Normal View History

/**
2016-03-24 13:01:20 -05:00
* Marlin 3D Printer Firmware
2020-02-03 08:00:57 -06:00
* Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin]
2011-11-18 15:17:37 -06:00
*
2016-03-24 13:01:20 -05:00
* Based on Sprinter and grbl.
2019-06-27 23:57:50 -05:00
* Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm
2011-11-18 15:17:37 -06:00
*
2016-03-24 13:01:20 -05:00
* This program is free software: you can redistribute it and/or modify
2011-11-18 15:17:37 -06:00
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
2016-03-24 13:01:20 -05:00
* This program is distributed in the hope that it will be useful,
2011-11-18 15:17:37 -06:00
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
2020-07-22 22:20:14 -05:00
* along with this program. If not, see <https://www.gnu.org/licenses/>.
2016-03-24 13:01:20 -05:00
*
*/
2020-02-22 19:26:52 -06:00
#if __GNUC__ > 8
#pragma GCC diagnostic ignored "-Waddress-of-packed-member"
#endif
/**
2020-10-24 17:13:10 -05:00
* sd/SdBaseFile.cpp
*
2016-03-24 13:01:20 -05:00
* Arduino SdFat Library
2019-06-27 23:57:50 -05:00
* Copyright (c) 2009 by William Greiman
2016-03-24 13:01:20 -05:00
*
* This file is part of the Arduino Sd2Card Library
2011-11-18 15:17:37 -06:00
*/
2017-09-06 06:28:32 -05:00
#include "../inc/MarlinConfig.h"
#if ENABLED(SDSUPPORT)
2011-11-18 15:17:37 -06:00
#include "SdBaseFile.h"
2017-09-06 06:28:32 -05:00
#include "../MarlinCore.h"
2017-11-15 00:06:20 -06:00
SdBaseFile* SdBaseFile::cwd_ = 0; // Pointer to Current Working Directory
2017-09-06 06:28:32 -05:00
2011-11-18 15:17:37 -06:00
// callback function for date/time
void (*SdBaseFile::dateTime_)(uint16_t* date, uint16_t* time) = 0;
2017-11-15 00:06:20 -06:00
2011-11-18 15:17:37 -06:00
// add a cluster to a file
bool SdBaseFile::addCluster() {
2020-05-30 23:59:29 -05:00
if (ENABLED(SDCARD_READONLY)) return false;
2017-11-15 00:06:20 -06:00
if (!vol_->allocContiguous(1, &curCluster_)) return false;
2011-11-18 15:17:37 -06:00
// if first cluster of file link to directory entry
if (firstCluster_ == 0) {
firstCluster_ = curCluster_;
flags_ |= F_FILE_DIR_DIRTY;
}
return true;
}
2017-11-15 00:06:20 -06:00
2011-11-18 15:17:37 -06:00
// Add a cluster to a directory file and zero the cluster.
// return with first block of cluster in the cache
bool SdBaseFile::addDirCluster() {
2020-05-30 23:59:29 -05:00
if (ENABLED(SDCARD_READONLY)) return false;
2011-11-18 15:17:37 -06:00
uint32_t block;
// max folder size
2017-11-15 00:06:20 -06:00
if (fileSize_ / sizeof(dir_t) >= 0xFFFF) return false;
2011-11-18 15:17:37 -06:00
2017-11-15 00:06:20 -06:00
if (!addCluster()) return false;
if (!vol_->cacheFlush()) return false;
2011-11-18 15:17:37 -06:00
block = vol_->clusterStartBlock(curCluster_);
// set cache to first block of cluster
vol_->cacheSetBlockNumber(block, true);
// zero first block of cluster
memset(vol_->cacheBuffer_.data, 0, 512);
// zero rest of cluster
for (uint8_t i = 1; i < vol_->blocksPerCluster_; i++) {
2017-11-15 00:06:20 -06:00
if (!vol_->writeBlock(block + i, vol_->cacheBuffer_.data)) return false;
2011-11-18 15:17:37 -06:00
}
// Increase directory file size by cluster size
fileSize_ += 512UL << vol_->clusterSizeShift_;
return true;
}
2017-11-15 00:06:20 -06:00
2011-11-18 15:17:37 -06:00
// cache a file's directory entry
// return pointer to cached entry or null for failure
dir_t* SdBaseFile::cacheDirEntry(uint8_t action) {
if (!vol_->cacheRawBlock(dirBlock_, action)) return nullptr;
2011-11-18 15:17:37 -06:00
return vol_->cache()->dir + dirIndex_;
}
2017-11-15 00:06:20 -06:00
/**
* Close a file and force cached data and directory information
2011-11-18 15:17:37 -06:00
* to be written to the storage device.
*
2017-11-15 00:06:20 -06:00
* \return true for success, false for failure.
2011-11-18 15:17:37 -06:00
* Reasons for failure include no file is open or an I/O error.
*/
bool SdBaseFile::close() {
bool rtn = sync();
type_ = FAT_FILE_TYPE_CLOSED;
return rtn;
}
2017-11-15 00:06:20 -06:00
/**
* Check for contiguous file and return its raw block range.
2011-11-18 15:17:37 -06:00
*
* \param[out] bgnBlock the first block address for the file.
* \param[out] endBlock the last block address for the file.
*
2017-11-15 00:06:20 -06:00
* \return true for success, false for failure.
2011-11-18 15:17:37 -06:00
* Reasons for failure include file is not contiguous, file has zero length
* or an I/O error occurred.
*/
bool SdBaseFile::contiguousRange(uint32_t* bgnBlock, uint32_t* endBlock) {
// error if no blocks
2017-11-15 00:06:20 -06:00
if (firstCluster_ == 0) return false;
2011-11-18 15:17:37 -06:00
for (uint32_t c = firstCluster_; ; c++) {
uint32_t next;
2017-11-15 00:06:20 -06:00
if (!vol_->fatGet(c, &next)) return false;
2011-11-18 15:17:37 -06:00
// check for contiguous
if (next != (c + 1)) {
// error if not end of chain
2017-11-15 00:06:20 -06:00
if (!vol_->isEOC(next)) return false;
2011-11-18 15:17:37 -06:00
*bgnBlock = vol_->clusterStartBlock(firstCluster_);
*endBlock = vol_->clusterStartBlock(c)
+ vol_->blocksPerCluster_ - 1;
return true;
}
}
return false;
}
2017-11-15 00:06:20 -06:00
/**
* Create and open a new contiguous file of a specified size.
2011-11-18 15:17:37 -06:00
*
* \note This function only supports short DOS 8.3 names.
* See open() for more information.
*
* \param[in] dirFile The directory where the file will be created.
* \param[in] path A path with a valid DOS 8.3 file name.
* \param[in] size The desired file size.
*
2017-11-15 00:06:20 -06:00
* \return true for success, false for failure.
2011-11-18 15:17:37 -06:00
* Reasons for failure include \a path contains
* an invalid DOS 8.3 file name, the FAT volume has not been initialized,
* a file is already open, the file already exists, the root
* directory is full or an I/O error.
*/
2017-11-15 00:06:20 -06:00
bool SdBaseFile::createContiguous(SdBaseFile* dirFile, const char* path, uint32_t size) {
2020-05-30 23:59:29 -05:00
if (ENABLED(SDCARD_READONLY)) return false;
2011-11-18 15:17:37 -06:00
uint32_t count;
// don't allow zero length file
2017-11-15 00:06:20 -06:00
if (size == 0) return false;
if (!open(dirFile, path, O_CREAT | O_EXCL | O_RDWR)) return false;
2011-11-18 15:17:37 -06:00
// calculate number of clusters needed
count = ((size - 1) >> (vol_->clusterSizeShift_ + 9)) + 1;
// allocate clusters
if (!vol_->allocContiguous(count, &firstCluster_)) {
remove();
2017-11-15 00:06:20 -06:00
return false;
2011-11-18 15:17:37 -06:00
}
fileSize_ = size;
// insure sync() will update dir entry
flags_ |= F_FILE_DIR_DIRTY;
return sync();
}
2017-11-15 00:06:20 -06:00
/**
* Return a file's directory entry.
2011-11-18 15:17:37 -06:00
*
* \param[out] dir Location for return of the file's directory entry.
*
2017-11-15 00:06:20 -06:00
* \return true for success, false for failure.
2011-11-18 15:17:37 -06:00
*/
bool SdBaseFile::dirEntry(dir_t* dir) {
dir_t* p;
// make sure fields on SD are correct
2017-11-15 00:06:20 -06:00
if (!sync()) return false;
2011-11-18 15:17:37 -06:00
// read entry
p = cacheDirEntry(SdVolume::CACHE_FOR_READ);
2017-11-15 00:06:20 -06:00
if (!p) return false;
2011-11-18 15:17:37 -06:00
// copy to caller's struct
memcpy(dir, p, sizeof(dir_t));
return true;
}
2017-11-15 00:06:20 -06:00
/**
* Format the name field of \a dir into the 13 byte array
2011-11-18 15:17:37 -06:00
* \a name in standard 8.3 short name format.
*
* \param[in] dir The directory structure containing the name.
* \param[out] name A 13 byte char array for the formatted name.
*/
void SdBaseFile::dirName(const dir_t& dir, char* name) {
uint8_t j = 0;
2020-03-13 23:18:16 -05:00
LOOP_L_N(i, 11) {
2011-11-18 15:17:37 -06:00
if (dir.name[i] == ' ')continue;
if (i == 8) name[j++] = '.';
name[j++] = dir.name[i];
}
name[j] = 0;
}
2017-11-15 00:06:20 -06:00
/**
* Test for the existence of a file in a directory
2011-11-18 15:17:37 -06:00
*
* \param[in] name Name of the file to be tested for.
*
* The calling instance must be an open directory file.
*
* dirFile.exists("TOFIND.TXT") searches for "TOFIND.TXT" in the directory
* dirFile.
*
* \return true if the file exists else false.
*/
bool SdBaseFile::exists(const char* name) {
SdBaseFile file;
return file.open(this, name, O_READ);
}
2017-11-15 00:06:20 -06:00
2011-11-18 15:17:37 -06:00
/**
* Get a string from a file.
*
* fgets() reads bytes from a file into the array pointed to by \a str, until
* \a num - 1 bytes are read, or a delimiter is read and transferred to \a str,
* or end-of-file is encountered. The string is then terminated
* with a null byte.
*
* fgets() deletes CR, '\\r', from the string. This insures only a '\\n'
* terminates the string for Windows text files which use CRLF for newline.
*
* \param[out] str Pointer to the array where the string is stored.
* \param[in] num Maximum number of characters to be read
* (including the final null byte). Usually the length
* of the array \a str is used.
* \param[in] delim Optional set of delimiters. The default is "\n".
*
* \return For success fgets() returns the length of the string in \a str.
* If no data is read, fgets() returns zero for EOF or -1 if an error occurred.
**/
int16_t SdBaseFile::fgets(char* str, int16_t num, char* delim) {
char ch;
int16_t n = 0;
int16_t r = -1;
while ((n + 1) < num && (r = read(&ch, 1)) == 1) {
// delete CR
if (ch == '\r') continue;
str[n++] = ch;
if (!delim) {
if (ch == '\n') break;
}
else {
2011-11-18 15:17:37 -06:00
if (strchr(delim, ch)) break;
}
}
if (r < 0) {
// read error
return -1;
}
str[n] = '\0';
return n;
}
2017-11-15 00:06:20 -06:00
/**
* Get a file's name
2011-11-18 15:17:37 -06:00
*
* \param[out] name An array of 13 characters for the file's name.
*
2017-11-15 00:06:20 -06:00
* \return true for success, false for failure.
2011-11-18 15:17:37 -06:00
*/
bool SdBaseFile::getDosName(char * const name) {
2011-11-18 15:17:37 -06:00
if (!isOpen()) return false;
if (isRoot()) {
name[0] = '/';
name[1] = '\0';
return true;
}
// cache entry
dir_t* p = cacheDirEntry(SdVolume::CACHE_FOR_READ);
if (!p) return false;
// format name
dirName(*p, name);
return true;
}
2017-11-15 00:06:20 -06:00
2016-02-10 22:49:25 -06:00
void SdBaseFile::getpos(filepos_t* pos) {
2011-11-18 15:17:37 -06:00
pos->position = curPosition_;
pos->cluster = curCluster_;
}
2017-11-15 00:06:20 -06:00
/**
* List directory contents.
2011-11-18 15:17:37 -06:00
*
* \param[in] pr Print stream for list.
*
* \param[in] flags The inclusive OR of
*
* LS_DATE - %Print file modification date
*
* LS_SIZE - %Print file size.
*
* LS_R - Recursive list of subdirectories.
*
* \param[in] indent Amount of space before file name. Used for recursive
* list to indicate subdirectory level.
*/
void SdBaseFile::ls(uint8_t flags, uint8_t indent) {
2011-11-18 15:17:37 -06:00
rewind();
int8_t status;
while ((status = lsPrintNext(flags, indent))) {
2011-11-18 15:17:37 -06:00
if (status > 1 && (flags & LS_R)) {
uint16_t index = curPosition() / 32 - 1;
2011-11-18 15:17:37 -06:00
SdBaseFile s;
if (s.open(this, index, O_READ)) s.ls(flags, indent + 2);
2011-11-18 15:17:37 -06:00
seekSet(32 * (index + 1));
}
}
}
2017-11-15 00:06:20 -06:00
2011-11-18 15:17:37 -06:00
// saves 32 bytes on stack for ls recursion
// return 0 - EOF, 1 - normal file, or 2 - directory
int8_t SdBaseFile::lsPrintNext(uint8_t flags, uint8_t indent) {
2011-11-18 15:17:37 -06:00
dir_t dir;
uint8_t w = 0;
while (1) {
if (read(&dir, sizeof(dir)) != sizeof(dir)) return 0;
if (dir.name[0] == DIR_NAME_FREE) return 0;
// skip deleted entry and entries for . and ..
if (dir.name[0] != DIR_NAME_DELETED && dir.name[0] != '.'
&& DIR_IS_FILE_OR_SUBDIR(&dir)) break;
2011-11-18 15:17:37 -06:00
}
// indent for dir level
2020-03-13 23:18:16 -05:00
LOOP_L_N(i, indent) SERIAL_CHAR(' ');
2011-11-18 15:17:37 -06:00
// print name
2020-03-13 23:18:16 -05:00
LOOP_L_N(i, 11) {
2011-11-18 15:17:37 -06:00
if (dir.name[i] == ' ')continue;
if (i == 8) {
2017-11-05 08:49:38 -06:00
SERIAL_CHAR('.');
2011-11-18 15:17:37 -06:00
w++;
}
2017-11-05 08:49:38 -06:00
SERIAL_CHAR(dir.name[i]);
2011-11-18 15:17:37 -06:00
w++;
}
if (DIR_IS_SUBDIR(&dir)) {
2017-11-05 08:49:38 -06:00
SERIAL_CHAR('/');
2011-11-18 15:17:37 -06:00
w++;
}
if (flags & (LS_DATE | LS_SIZE)) {
2017-11-05 08:49:38 -06:00
while (w++ < 14) SERIAL_CHAR(' ');
2011-11-18 15:17:37 -06:00
}
// print modify date/time if requested
if (flags & LS_DATE) {
2017-11-05 08:49:38 -06:00
SERIAL_CHAR(' ');
printFatDate(dir.lastWriteDate);
2017-11-05 08:49:38 -06:00
SERIAL_CHAR(' ');
printFatTime(dir.lastWriteTime);
2011-11-18 15:17:37 -06:00
}
// print size if requested
if (!DIR_IS_SUBDIR(&dir) && (flags & LS_SIZE)) {
2017-11-05 08:49:38 -06:00
SERIAL_CHAR(' ');
SERIAL_ECHO(dir.fileSize);
2011-11-18 15:17:37 -06:00
}
2017-11-05 08:49:38 -06:00
SERIAL_EOL();
2011-11-18 15:17:37 -06:00
return DIR_IS_FILE(&dir) ? 1 : 2;
}
2017-11-15 00:06:20 -06:00
// Format directory name field from a 8.3 name string
2011-11-18 15:17:37 -06:00
bool SdBaseFile::make83Name(const char* str, uint8_t* name, const char** ptr) {
2017-11-15 00:06:20 -06:00
uint8_t n = 7, // Max index until a dot is found
i = 11;
while (i) name[--i] = ' '; // Set whole FILENAME.EXT to spaces
while (*str && *str != '/') { // For each character, until nul or '/'
uint8_t c = *str++; // Get char and advance
if (c == '.') { // For a dot...
if (n == 10) return false; // Already moved the max index? fail!
n = 10; // Move the max index for full 8.3 name
i = 8; // Move up to the extension place
}
else {
2017-11-15 00:06:20 -06:00
// Fail for illegal characters
2011-11-18 15:17:37 -06:00
PGM_P p = PSTR("|<>^+=?/[];,*\"\\");
2017-11-15 00:06:20 -06:00
while (uint8_t b = pgm_read_byte(p++)) if (b == c) return false;
if (i > n || c < 0x21 || c == 0x7F) return false; // Check size, non-printable characters
name[i++] = (c < 'a' || c > 'z') ? (c) : (c + ('A' - 'a')); // Uppercase required for 8.3 name
2011-11-18 15:17:37 -06:00
}
}
2017-11-15 00:06:20 -06:00
*ptr = str; // Set passed pointer to the end
return name[0] != ' '; // Return true if any name was set
2011-11-18 15:17:37 -06:00
}
2017-11-15 00:06:20 -06:00
/**
* Make a new directory.
2011-11-18 15:17:37 -06:00
*
* \param[in] parent An open SdFat instance for the directory that will contain
* the new directory.
*
* \param[in] path A path with a valid 8.3 DOS name for the new directory.
*
* \param[in] pFlag Create missing parent directories if true.
*
2017-11-15 00:06:20 -06:00
* \return true for success, false for failure.
2011-11-18 15:17:37 -06:00
* Reasons for failure include this file is already open, \a parent is not a
* directory, \a path is invalid or already exists in \a parent.
*/
bool SdBaseFile::mkdir(SdBaseFile* parent, const char* path, bool pFlag) {
2020-05-30 23:59:29 -05:00
if (ENABLED(SDCARD_READONLY)) return false;
2011-11-18 15:17:37 -06:00
uint8_t dname[11];
SdBaseFile dir1, dir2;
SdBaseFile* sub = &dir1;
SdBaseFile* start = parent;
2017-11-15 00:06:20 -06:00
if (!parent || isOpen()) return false;
2011-11-18 15:17:37 -06:00
if (*path == '/') {
while (*path == '/') path++;
if (!parent->isRoot()) {
2017-11-15 00:06:20 -06:00
if (!dir2.openRoot(parent->vol_)) return false;
2011-11-18 15:17:37 -06:00
parent = &dir2;
}
}
while (1) {
2017-11-15 00:06:20 -06:00
if (!make83Name(path, dname, &path)) return false;
2011-11-18 15:17:37 -06:00
while (*path == '/') path++;
if (!*path) break;
if (!sub->open(parent, dname, O_READ)) {
2017-11-15 00:06:20 -06:00
if (!pFlag || !sub->mkdir(parent, dname))
return false;
2011-11-18 15:17:37 -06:00
}
if (parent != start) parent->close();
parent = sub;
sub = parent != &dir1 ? &dir1 : &dir2;
}
return mkdir(parent, dname);
}
2017-11-15 00:06:20 -06:00
2011-11-18 15:17:37 -06:00
bool SdBaseFile::mkdir(SdBaseFile* parent, const uint8_t dname[11]) {
2020-05-30 23:59:29 -05:00
if (ENABLED(SDCARD_READONLY)) return false;
2011-11-18 15:17:37 -06:00
uint32_t block;
dir_t d;
dir_t* p;
2017-11-15 00:06:20 -06:00
if (!parent->isDir()) return false;
2011-11-18 15:17:37 -06:00
// create a normal file
2017-11-15 00:06:20 -06:00
if (!open(parent, dname, O_CREAT | O_EXCL | O_RDWR)) return false;
2011-11-18 15:17:37 -06:00
// convert file to directory
flags_ = O_READ;
type_ = FAT_FILE_TYPE_SUBDIR;
// allocate and zero first cluster
2017-11-15 00:06:20 -06:00
if (!addDirCluster()) return false;
2011-11-18 15:17:37 -06:00
// force entry to SD
2017-11-15 00:06:20 -06:00
if (!sync()) return false;
2011-11-18 15:17:37 -06:00
// cache entry - should already be in cache due to sync() call
p = cacheDirEntry(SdVolume::CACHE_FOR_WRITE);
2017-11-15 00:06:20 -06:00
if (!p) return false;
2011-11-18 15:17:37 -06:00
// change directory entry attribute
p->attributes = DIR_ATT_DIRECTORY;
// make entry for '.'
memcpy(&d, p, sizeof(d));
d.name[0] = '.';
2020-03-13 23:18:16 -05:00
LOOP_S_L_N(i, 1, 11) d.name[i] = ' ';
2011-11-18 15:17:37 -06:00
// cache block for '.' and '..'
block = vol_->clusterStartBlock(firstCluster_);
2017-11-15 00:06:20 -06:00
if (!vol_->cacheRawBlock(block, SdVolume::CACHE_FOR_WRITE)) return false;
2011-11-18 15:17:37 -06:00
// copy '.' to block
memcpy(&vol_->cache()->dir[0], &d, sizeof(d));
// make entry for '..'
d.name[1] = '.';
if (parent->isRoot()) {
d.firstClusterLow = 0;
d.firstClusterHigh = 0;
}
else {
2017-08-09 13:23:14 -05:00
d.firstClusterLow = parent->firstCluster_ & 0xFFFF;
2011-11-18 15:17:37 -06:00
d.firstClusterHigh = parent->firstCluster_ >> 16;
}
// copy '..' to block
memcpy(&vol_->cache()->dir[1], &d, sizeof(d));
// write first block
return vol_->cacheFlush();
}
2017-11-15 00:06:20 -06:00
/**
* Open a file in the current working directory.
*
* \param[in] path A path with a valid 8.3 DOS name for a file to be opened.
*
* \param[in] oflag Values for \a oflag are constructed by a bitwise-inclusive
* OR of open flags. see SdBaseFile::open(SdBaseFile*, const char*, uint8_t).
*
2017-11-15 00:06:20 -06:00
* \return true for success, false for failure.
*/
bool SdBaseFile::open(const char* path, uint8_t oflag) {
return open(cwd_, path, oflag);
}
2017-11-15 00:06:20 -06:00
/**
* Open a file or directory by name.
2011-11-18 15:17:37 -06:00
*
* \param[in] dirFile An open SdFat instance for the directory containing the
* file to be opened.
*
* \param[in] path A path with a valid 8.3 DOS name for a file to be opened.
*
* \param[in] oflag Values for \a oflag are constructed by a bitwise-inclusive
* OR of flags from the following list
*
* O_READ - Open for reading.
*
* O_RDONLY - Same as O_READ.
*
* O_WRITE - Open for writing.
*
* O_WRONLY - Same as O_WRITE.
*
* O_RDWR - Open for reading and writing.
*
* O_APPEND - If set, the file offset shall be set to the end of the
* file prior to each write.
*
* O_AT_END - Set the initial position at the end of the file.
*
* O_CREAT - If the file exists, this flag has no effect except as noted
* under O_EXCL below. Otherwise, the file shall be created
*
* O_EXCL - If O_CREAT and O_EXCL are set, open() shall fail if the file exists.
*
* O_SYNC - Call sync() after each write. This flag should not be used with
* write(uint8_t), write_P(PGM_P), writeln_P(PGM_P), or the Arduino Print class.
* These functions do character at a time writes so sync() will be called
* after each byte.
*
* O_TRUNC - If the file exists and is a regular file, and the file is
* successfully opened and is not read only, its length shall be truncated to 0.
*
* WARNING: A given file must not be opened by more than one SdBaseFile object
* of file corruption may occur.
*
* \note Directory files must be opened read only. Write and truncation is
* not allowed for directory files.
*
2017-11-15 00:06:20 -06:00
* \return true for success, false for failure.
2011-11-18 15:17:37 -06:00
* Reasons for failure include this file is already open, \a dirFile is not
* a directory, \a path is invalid, the file does not exist
* or can't be opened in the access mode specified by oflag.
*/
bool SdBaseFile::open(SdBaseFile* dirFile, const char* path, uint8_t oflag) {
uint8_t dname[11];
SdBaseFile dir1, dir2;
2017-11-15 00:06:20 -06:00
SdBaseFile *parent = dirFile, *sub = &dir1;
2011-11-18 15:17:37 -06:00
2017-11-15 00:06:20 -06:00
if (!dirFile || isOpen()) return false;
2011-11-18 15:17:37 -06:00
2017-11-15 00:06:20 -06:00
if (*path == '/') { // Path starts with '/'
if (!dirFile->isRoot()) { // Is the passed dirFile the root?
if (!dir2.openRoot(dirFile->vol_)) return false; // Get the root in dir2, if possible
parent = &dir2; // Change 'parent' to point at the root dir
2011-11-18 15:17:37 -06:00
}
2017-11-15 00:06:20 -06:00
while (*path == '/') path++; // Skip all leading slashes
2011-11-18 15:17:37 -06:00
}
2017-11-15 00:06:20 -06:00
for (;;) {
if (!make83Name(path, dname, &path)) return false;
2011-11-18 15:17:37 -06:00
while (*path == '/') path++;
if (!*path) break;
2017-11-15 00:06:20 -06:00
if (!sub->open(parent, dname, O_READ)) return false;
2011-11-18 15:17:37 -06:00
if (parent != dirFile) parent->close();
parent = sub;
sub = parent != &dir1 ? &dir1 : &dir2;
}
return open(parent, dname, oflag);
}
2017-11-15 00:06:20 -06:00
2011-11-18 15:17:37 -06:00
// open with filename in dname
2017-11-15 00:06:20 -06:00
bool SdBaseFile::open(SdBaseFile* dirFile, const uint8_t dname[11], uint8_t oflag) {
bool emptyFound = false, fileFound = false;
2011-11-18 15:17:37 -06:00
uint8_t index;
dir_t* p;
vol_ = dirFile->vol_;
dirFile->rewind();
// search for file
while (dirFile->curPosition_ < dirFile->fileSize_) {
2017-12-15 15:17:52 -06:00
index = 0xF & (dirFile->curPosition_ >> 5);
2011-11-18 15:17:37 -06:00
p = dirFile->readDirCache();
2017-11-15 00:06:20 -06:00
if (!p) return false;
2011-11-18 15:17:37 -06:00
if (p->name[0] == DIR_NAME_FREE || p->name[0] == DIR_NAME_DELETED) {
// remember first empty slot
if (!emptyFound) {
dirBlock_ = dirFile->vol_->cacheBlockNumber();
dirIndex_ = index;
emptyFound = true;
}
// done if no entries follow
if (p->name[0] == DIR_NAME_FREE) break;
}
else if (!memcmp(dname, p->name, 11)) {
2011-11-18 15:17:37 -06:00
fileFound = true;
break;
}
}
if (fileFound) {
// don't open existing file if O_EXCL
2017-11-15 00:06:20 -06:00
if (oflag & O_EXCL) return false;
}
else {
2011-11-18 15:17:37 -06:00
// don't create unless O_CREAT and O_WRITE
2020-05-30 23:59:29 -05:00
if ((oflag & (O_CREAT | O_WRITE)) != (O_CREAT | O_WRITE)) return false;
2011-11-18 15:17:37 -06:00
if (emptyFound) {
index = dirIndex_;
p = cacheDirEntry(SdVolume::CACHE_FOR_WRITE);
2017-11-15 00:06:20 -06:00
if (!p) return false;
}
else {
2017-11-15 00:06:20 -06:00
if (dirFile->type_ == FAT_FILE_TYPE_ROOT_FIXED) return false;
2011-11-18 15:17:37 -06:00
// add and zero cluster for dirFile - first cluster is in cache for write
2017-11-15 00:06:20 -06:00
if (!dirFile->addDirCluster()) return false;
2011-11-18 15:17:37 -06:00
// use first entry in cluster
p = dirFile->vol_->cache()->dir;
index = 0;
}
// initialize as empty file
2016-10-25 22:59:40 -05:00
memset(p, 0, sizeof(*p));
2011-11-18 15:17:37 -06:00
memcpy(p->name, dname, 11);
// set timestamps
if (dateTime_) {
// call user date/time function
dateTime_(&p->creationDate, &p->creationTime);
}
else {
2011-11-18 15:17:37 -06:00
// use default date/time
p->creationDate = FAT_DEFAULT_DATE;
p->creationTime = FAT_DEFAULT_TIME;
}
p->lastAccessDate = p->creationDate;
p->lastWriteDate = p->creationDate;
p->lastWriteTime = p->creationTime;
// write entry to SD
2017-11-15 00:06:20 -06:00
if (!dirFile->vol_->cacheFlush()) return false;
2011-11-18 15:17:37 -06:00
}
// open entry in cache
return openCachedEntry(index, oflag);
}
2017-11-15 00:06:20 -06:00
/**
* Open a file by index.
2011-11-18 15:17:37 -06:00
*
* \param[in] dirFile An open SdFat instance for the directory.
*
* \param[in] index The \a index of the directory entry for the file to be
* opened. The value for \a index is (directory file position)/32.
*
* \param[in] oflag Values for \a oflag are constructed by a bitwise-inclusive
* OR of flags O_READ, O_WRITE, O_TRUNC, and O_SYNC.
*
* See open() by path for definition of flags.
* \return true for success or false for failure.
*/
bool SdBaseFile::open(SdBaseFile* dirFile, uint16_t index, uint8_t oflag) {
dir_t* p;
vol_ = dirFile->vol_;
// error if already open
2017-11-15 00:06:20 -06:00
if (isOpen() || !dirFile) return false;
2011-11-18 15:17:37 -06:00
// don't open existing file if O_EXCL - user call error
2017-11-15 00:06:20 -06:00
if (oflag & O_EXCL) return false;
2011-11-18 15:17:37 -06:00
// seek to location of entry
2017-11-15 00:06:20 -06:00
if (!dirFile->seekSet(32 * index)) return false;
2011-11-18 15:17:37 -06:00
// read entry into cache
p = dirFile->readDirCache();
2017-11-15 00:06:20 -06:00
if (!p) return false;
2011-11-18 15:17:37 -06:00
// error if empty slot or '.' or '..'
if (p->name[0] == DIR_NAME_FREE ||
p->name[0] == DIR_NAME_DELETED || p->name[0] == '.') {
2017-11-15 00:06:20 -06:00
return false;
2011-11-18 15:17:37 -06:00
}
// open cached entry
2017-12-15 15:17:52 -06:00
return openCachedEntry(index & 0xF, oflag);
2011-11-18 15:17:37 -06:00
}
2017-11-15 00:06:20 -06:00
2011-11-18 15:17:37 -06:00
// open a cached directory entry. Assumes vol_ is initialized
bool SdBaseFile::openCachedEntry(uint8_t dirIndex, uint8_t oflag) {
2020-05-30 23:59:29 -05:00
dir_t* p;
#if ENABLED(SDCARD_READONLY)
if (oflag & (O_WRITE | O_CREAT | O_TRUNC)) goto FAIL;
#endif
2011-11-18 15:17:37 -06:00
// location of entry in cache
2020-05-30 23:59:29 -05:00
p = &vol_->cache()->dir[dirIndex];
2011-11-18 15:17:37 -06:00
// write or truncate is an error for a directory or read-only file
if (p->attributes & (DIR_ATT_READ_ONLY | DIR_ATT_DIRECTORY)) {
2017-08-11 15:55:07 -05:00
if (oflag & (O_WRITE | O_TRUNC)) goto FAIL;
2011-11-18 15:17:37 -06:00
}
// remember location of directory entry on SD
dirBlock_ = vol_->cacheBlockNumber();
dirIndex_ = dirIndex;
// copy first cluster number for directory fields
firstCluster_ = (uint32_t)p->firstClusterHigh << 16;
firstCluster_ |= p->firstClusterLow;
// make sure it is a normal file or subdirectory
if (DIR_IS_FILE(p)) {
fileSize_ = p->fileSize;
type_ = FAT_FILE_TYPE_NORMAL;
}
else if (DIR_IS_SUBDIR(p)) {
2017-08-11 15:55:07 -05:00
if (!vol_->chainSize(firstCluster_, &fileSize_)) goto FAIL;
2011-11-18 15:17:37 -06:00
type_ = FAT_FILE_TYPE_SUBDIR;
}
2017-11-15 00:06:20 -06:00
else
2017-08-11 15:55:07 -05:00
goto FAIL;
2017-11-15 00:06:20 -06:00
2011-11-18 15:17:37 -06:00
// save open flags for read/write
flags_ = oflag & F_OFLAG;
// set to start of file
curCluster_ = 0;
curPosition_ = 0;
if ((oflag & O_TRUNC) && !truncate(0)) return false;
return oflag & O_AT_END ? seekEnd(0) : true;
2017-11-15 00:06:20 -06:00
2017-08-11 15:55:07 -05:00
FAIL:
2011-11-18 15:17:37 -06:00
type_ = FAT_FILE_TYPE_CLOSED;
return false;
}
2017-11-15 00:06:20 -06:00
/**
* Open the next file or subdirectory in a directory.
2011-11-18 15:17:37 -06:00
*
* \param[in] dirFile An open SdFat instance for the directory containing the
* file to be opened.
*
* \param[in] oflag Values for \a oflag are constructed by a bitwise-inclusive
* OR of flags O_READ, O_WRITE, O_TRUNC, and O_SYNC.
*
* See open() by path for definition of flags.
* \return true for success or false for failure.
*/
bool SdBaseFile::openNext(SdBaseFile* dirFile, uint8_t oflag) {
dir_t* p;
uint8_t index;
2017-11-15 00:06:20 -06:00
if (!dirFile) return false;
2011-11-18 15:17:37 -06:00
// error if already open
2017-11-15 00:06:20 -06:00
if (isOpen()) return false;
2011-11-18 15:17:37 -06:00
vol_ = dirFile->vol_;
while (1) {
2017-12-15 15:17:52 -06:00
index = 0xF & (dirFile->curPosition_ >> 5);
2011-11-18 15:17:37 -06:00
// read entry into cache
p = dirFile->readDirCache();
2017-11-15 00:06:20 -06:00
if (!p) return false;
2011-11-18 15:17:37 -06:00
// done if last entry
2017-11-15 00:06:20 -06:00
if (p->name[0] == DIR_NAME_FREE) return false;
2011-11-18 15:17:37 -06:00
// skip empty slot or '.' or '..'
if (p->name[0] == DIR_NAME_DELETED || p->name[0] == '.') {
continue;
}
// must be file or dir
if (DIR_IS_FILE_OR_SUBDIR(p)) {
return openCachedEntry(index, oflag);
}
}
return false;
}
2017-11-15 00:06:20 -06:00
#if 0
/**
* Open a directory's parent directory.
2011-11-18 15:17:37 -06:00
*
* \param[in] dir Parent of this directory will be opened. Must not be root.
*
2017-11-15 00:06:20 -06:00
* \return true for success, false for failure.
2011-11-18 15:17:37 -06:00
*/
bool SdBaseFile::openParent(SdBaseFile* dir) {
dir_t entry;
dir_t* p;
SdBaseFile file;
uint32_t c;
uint32_t cluster;
uint32_t lbn;
// error if already open or dir is root or dir is not a directory
2017-11-15 00:06:20 -06:00
if (isOpen() || !dir || dir->isRoot() || !dir->isDir()) return false;
2011-11-18 15:17:37 -06:00
vol_ = dir->vol_;
// position to '..'
2017-11-15 00:06:20 -06:00
if (!dir->seekSet(32)) return false;
2011-11-18 15:17:37 -06:00
// read '..' entry
2017-11-15 00:06:20 -06:00
if (dir->read(&entry, sizeof(entry)) != 32) return false;
2011-11-18 15:17:37 -06:00
// verify it is '..'
2017-11-15 00:06:20 -06:00
if (entry.name[0] != '.' || entry.name[1] != '.') return false;
2011-11-18 15:17:37 -06:00
// start cluster for '..'
cluster = entry.firstClusterLow;
cluster |= (uint32_t)entry.firstClusterHigh << 16;
if (cluster == 0) return openRoot(vol_);
// start block for '..'
lbn = vol_->clusterStartBlock(cluster);
// first block of parent dir
2017-11-15 00:06:20 -06:00
if (!vol_->cacheRawBlock(lbn, SdVolume::CACHE_FOR_READ)) return false;
2011-11-18 15:17:37 -06:00
p = &vol_->cacheBuffer_.dir[1];
// verify name for '../..'
2017-11-15 00:06:20 -06:00
if (p->name[0] != '.' || p->name[1] != '.') return false;
2011-11-18 15:17:37 -06:00
// '..' is pointer to first cluster of parent. open '../..' to find parent
if (p->firstClusterHigh == 0 && p->firstClusterLow == 0) {
2017-11-15 00:06:20 -06:00
if (!file.openRoot(dir->volume())) return false;
2011-11-18 15:17:37 -06:00
}
2017-11-15 00:06:20 -06:00
else if (!file.openCachedEntry(1, O_READ))
return false;
2011-11-18 15:17:37 -06:00
// search for parent in '../..'
do {
if (file.readDir(&entry, nullptr) != 32) return false;
2011-11-18 15:17:37 -06:00
c = entry.firstClusterLow;
c |= (uint32_t)entry.firstClusterHigh << 16;
} while (c != cluster);
2017-11-15 00:06:20 -06:00
2011-11-18 15:17:37 -06:00
// open parent
return open(&file, file.curPosition() / 32 - 1, O_READ);
2011-11-18 15:17:37 -06:00
}
2017-11-15 00:06:20 -06:00
#endif
/**
* Open a volume's root directory.
2011-11-18 15:17:37 -06:00
*
* \param[in] vol The FAT volume containing the root directory to be opened.
*
2017-11-15 00:06:20 -06:00
* \return true for success, false for failure.
2011-11-18 15:17:37 -06:00
* Reasons for failure include the file is already open, the FAT volume has
* not been initialized or it a FAT12 volume.
*/
bool SdBaseFile::openRoot(SdVolume* vol) {
// error if file is already open
2017-11-15 00:06:20 -06:00
if (isOpen()) return false;
2011-11-18 15:17:37 -06:00
if (vol->fatType() == 16 || (FAT12_SUPPORT && vol->fatType() == 12)) {
type_ = FAT_FILE_TYPE_ROOT_FIXED;
firstCluster_ = 0;
fileSize_ = 32 * vol->rootDirEntryCount();
}
else if (vol->fatType() == 32) {
2011-11-18 15:17:37 -06:00
type_ = FAT_FILE_TYPE_ROOT32;
firstCluster_ = vol->rootDirStart();
2017-11-15 00:06:20 -06:00
if (!vol->chainSize(firstCluster_, &fileSize_)) return false;
}
2017-11-15 00:06:20 -06:00
else // volume is not initialized, invalid, or FAT12 without support
2011-11-18 15:17:37 -06:00
return false;
2017-11-15 00:06:20 -06:00
2011-11-18 15:17:37 -06:00
vol_ = vol;
// read only
flags_ = O_READ;
// set to start of file
2017-11-15 00:06:20 -06:00
curCluster_ = curPosition_ = 0;
2011-11-18 15:17:37 -06:00
// root has no directory entry
2017-11-15 00:06:20 -06:00
dirBlock_ = dirIndex_ = 0;
2011-11-18 15:17:37 -06:00
return true;
}
2017-11-15 00:06:20 -06:00
/**
* Return the next available byte without consuming it.
2011-11-18 15:17:37 -06:00
*
* \return The byte if no error and not at eof else -1;
*/
int SdBaseFile::peek() {
2016-02-10 22:49:25 -06:00
filepos_t pos;
2011-11-18 15:17:37 -06:00
getpos(&pos);
int c = read();
if (c >= 0) setpos(&pos);
return c;
}
2011-11-18 15:17:37 -06:00
// print uint8_t with width 2
2017-11-05 08:49:38 -06:00
static void print2u(const uint8_t v) {
if (v < 10) SERIAL_CHAR('0');
SERIAL_ECHO(int(v));
2011-11-18 15:17:37 -06:00
}
2017-11-15 00:06:20 -06:00
/**
* %Print a directory date field to Serial.
2011-11-18 15:17:37 -06:00
*
* Format is yyyy-mm-dd.
*
* \param[in] fatDate The date field from a directory entry.
*/
2017-11-15 00:06:20 -06:00
/**
* %Print a directory date field.
2011-11-18 15:17:37 -06:00
*
* Format is yyyy-mm-dd.
*
* \param[in] pr Print stream for output.
* \param[in] fatDate The date field from a directory entry.
*/
void SdBaseFile::printFatDate(uint16_t fatDate) {
2017-11-05 08:49:38 -06:00
SERIAL_ECHO(FAT_YEAR(fatDate));
SERIAL_CHAR('-');
print2u(FAT_MONTH(fatDate));
2017-11-05 08:49:38 -06:00
SERIAL_CHAR('-');
print2u(FAT_DAY(fatDate));
2011-11-18 15:17:37 -06:00
}
2017-11-15 00:06:20 -06:00
/**
* %Print a directory time field.
2011-11-18 15:17:37 -06:00
*
* Format is hh:mm:ss.
*
* \param[in] pr Print stream for output.
* \param[in] fatTime The time field from a directory entry.
*/
void SdBaseFile::printFatTime(uint16_t fatTime) {
print2u(FAT_HOUR(fatTime));
2017-11-05 08:49:38 -06:00
SERIAL_CHAR(':');
print2u(FAT_MINUTE(fatTime));
2017-11-05 08:49:38 -06:00
SERIAL_CHAR(':');
print2u(FAT_SECOND(fatTime));
2011-11-18 15:17:37 -06:00
}
2017-11-15 00:06:20 -06:00
/**
* Print a file's name to Serial
2011-11-18 15:17:37 -06:00
*
2017-11-15 00:06:20 -06:00
* \return true for success, false for failure.
2011-11-18 15:17:37 -06:00
*/
bool SdBaseFile::printName() {
char name[FILENAME_LENGTH];
if (!getDosName(name)) return false;
2017-11-05 08:49:38 -06:00
SERIAL_ECHO(name);
2011-11-18 15:17:37 -06:00
return true;
}
2017-11-15 00:06:20 -06:00
/**
* Read the next byte from a file.
2011-11-18 15:17:37 -06:00
*
* \return For success read returns the next byte in the file as an int.
* If an error occurs or end of file is reached -1 is returned.
*/
int16_t SdBaseFile::read() {
uint8_t b;
return read(&b, 1) == 1 ? b : -1;
}
2017-11-15 00:06:20 -06:00
/**
* Read data from a file starting at the current position.
2011-11-18 15:17:37 -06:00
*
* \param[out] buf Pointer to the location that will receive the data.
*
* \param[in] nbyte Maximum number of bytes to read.
*
* \return For success read() returns the number of bytes read.
* A value less than \a nbyte, including zero, will be returned
* if end of file is reached.
* If an error occurs, read() returns -1. Possible errors include
* read() called before a file has been opened, corrupt file system
* or an I/O error occurred.
*/
int16_t SdBaseFile::read(void* buf, uint16_t nbyte) {
uint8_t* dst = reinterpret_cast<uint8_t*>(buf);
2017-11-15 00:06:20 -06:00
uint16_t offset, toRead;
2011-11-18 15:17:37 -06:00
uint32_t block; // raw device block number
// error if not open or write only
2017-11-15 00:06:20 -06:00
if (!isOpen() || !(flags_ & O_READ)) return -1;
2011-11-18 15:17:37 -06:00
// max bytes left in file
NOMORE(nbyte, fileSize_ - curPosition_);
2011-11-18 15:17:37 -06:00
// amount left to read
toRead = nbyte;
while (toRead > 0) {
2017-08-09 13:23:14 -05:00
offset = curPosition_ & 0x1FF; // offset in block
2011-11-18 15:17:37 -06:00
if (type_ == FAT_FILE_TYPE_ROOT_FIXED) {
block = vol_->rootDirStart() + (curPosition_ >> 9);
}
else {
2011-11-18 15:17:37 -06:00
uint8_t blockOfCluster = vol_->blockOfCluster(curPosition_);
if (offset == 0 && blockOfCluster == 0) {
// start of new cluster
2017-11-15 00:06:20 -06:00
if (curPosition_ == 0)
curCluster_ = firstCluster_; // use first cluster in file
else if (!vol_->fatGet(curCluster_, &curCluster_)) // get next cluster from FAT
return -1;
2011-11-18 15:17:37 -06:00
}
block = vol_->clusterStartBlock(curCluster_) + blockOfCluster;
}
uint16_t n = toRead;
// amount to be read from current block
NOMORE(n, 512 - offset);
2011-11-18 15:17:37 -06:00
// no buffering needed if n == 512
if (n == 512 && block != vol_->cacheBlockNumber()) {
2017-11-15 00:06:20 -06:00
if (!vol_->readBlock(block, dst)) return -1;
}
else {
2011-11-18 15:17:37 -06:00
// read block to cache and copy data to caller
2017-11-15 00:06:20 -06:00
if (!vol_->cacheRawBlock(block, SdVolume::CACHE_FOR_READ)) return -1;
2011-11-18 15:17:37 -06:00
uint8_t* src = vol_->cache()->data + offset;
memcpy(dst, src, n);
}
dst += n;
curPosition_ += n;
toRead -= n;
}
return nbyte;
}
2015-05-15 05:23:49 -05:00
/**
* Read the next entry in a directory.
2011-11-18 15:17:37 -06:00
*
* \param[out] dir The dir_t struct that will receive the data.
*
* \return For success readDir() returns the number of bytes read.
* A value of zero will be returned if end of file is reached.
* If an error occurs, readDir() returns -1. Possible errors include
* readDir() called before a directory has been opened, this is not
* a directory file or an I/O error occurred.
*/
2012-08-22 07:49:57 -05:00
int8_t SdBaseFile::readDir(dir_t* dir, char* longFilename) {
2011-11-18 15:17:37 -06:00
int16_t n;
// if not a directory file or miss-positioned return an error
2017-08-09 13:23:14 -05:00
if (!isDir() || (0x1F & curPosition_)) return -1;
// If we have a longFilename buffer, mark it as invalid.
// If a long filename is found it will be filled automatically.
if (longFilename) longFilename[0] = '\0';
2011-11-18 15:17:37 -06:00
while (1) {
2011-11-18 15:17:37 -06:00
n = read(dir, sizeof(dir_t));
2017-11-26 18:25:00 -06:00
if (n != sizeof(dir_t)) return n ? -1 : 0;
2011-11-18 15:17:37 -06:00
// last entry if DIR_NAME_FREE
if (dir->name[0] == DIR_NAME_FREE) return 0;
// skip deleted entry and entry for . and ..
if (dir->name[0] == DIR_NAME_DELETED || dir->name[0] == '.') {
if (longFilename) longFilename[0] = '\0'; // Invalidate erased file long name, if any
continue;
}
// Fill the long filename if we have a long filename entry.
// Long filename entries are stored before the short filename.
if (longFilename && DIR_IS_LONG_NAME(dir)) {
vfat_t* VFAT = (vfat_t*)dir;
2015-05-15 05:23:49 -05:00
// Sanity-check the VFAT entry. The first cluster is always set to zero. And the sequence number should be higher than 0
2017-11-26 18:25:00 -06:00
if (VFAT->firstClusterLow == 0) {
const uint8_t seq = VFAT->sequenceNumber & 0x1F;
if (WITHIN(seq, 1, MAX_VFAT_ENTRIES)) {
// TODO: Store the filename checksum to verify if a long-filename-unaware system modified the file table.
n = (seq - 1) * (FILENAME_LENGTH);
LOOP_L_N(i, FILENAME_LENGTH) {
uint16_t utf16_ch = (i < 5) ? VFAT->name1[i] : (i < 11) ? VFAT->name2[i - 5] : VFAT->name3[i - 11];
#if ENABLED(UTF_FILENAME_SUPPORT)
// We can't reconvert to UTF-8 here as UTF-8 is variable-size encoding, but joining LFN blocks
// needs static bytes addressing. So here just store full UTF-16LE words to re-convert later.
uint16_t idx = (n + i) * 2; // This is fixed as FAT LFN always contain UTF-16LE encoding
2020-11-12 22:26:49 -06:00
longFilename[idx] = utf16_ch & 0xFF;
longFilename[idx + 1] = (utf16_ch >> 8) & 0xFF;
#else
// Replace all multibyte characters to '_'
longFilename[n + i] = (utf16_ch > 0xFF) ? '_' : (utf16_ch & 0xFF);
#endif
}
2017-11-26 18:25:00 -06:00
// If this VFAT entry is the last one, add a NUL terminator at the end of the string
if (VFAT->sequenceNumber & 0x40) longFilename[(n + FILENAME_LENGTH) * LONG_FILENAME_CHARSIZE] = '\0';
2017-11-26 18:25:00 -06:00
}
2015-05-15 05:23:49 -05:00
}
2012-08-22 07:49:57 -05:00
}
2020-11-12 22:26:49 -06:00
// Post-process normal file or subdirectory longname, if any
if (DIR_IS_FILE_OR_SUBDIR(dir)) {
#if ENABLED(UTF_FILENAME_SUPPORT)
#if LONG_FILENAME_CHARSIZE > 2
// Add warning for developers for currently not supported 3-byte cases (Conversion series of 2-byte
// codepoints to 3-byte in-place will break the rest of filename)
#error "Currently filename re-encoding is done in-place. It may break the remaining chars to use 3-byte codepoints."
#endif
2020-11-12 22:26:49 -06:00
// Is there a long filename to decode?
if (longFilename) {
// Reset n to the start of the long name
n = 0;
for (uint16_t idx = 0; idx < (LONG_FILENAME_LENGTH) / 2; idx += 2) { // idx is fixed since FAT LFN always contains UTF-16LE encoding
uint16_t utf16_ch = longFilename[idx] | (longFilename[idx + 1] << 8);
if (0xD800 == (utf16_ch & 0xF800)) // Surrogate pair - encode as '_'
longFilename[n++] = '_';
else if (0 == (utf16_ch & 0xFF80)) // Encode as 1-byte UTF-8 char
longFilename[n++] = utf16_ch & 0x007F;
else if (0 == (utf16_ch & 0xF800)) { // Encode as 2-byte UTF-8 char
longFilename[n++] = 0xC0 | ((utf16_ch >> 6) & 0x1F);
longFilename[n++] = 0x80 | ( utf16_ch & 0x3F);
}
else {
#if LONG_FILENAME_CHARSIZE > 2 // Encode as 3-byte UTF-8 char
longFilename[n++] = 0xE0 | ((utf16_ch >> 12) & 0x0F);
longFilename[n++] = 0xC0 | ((utf16_ch >> 6) & 0x3F);
longFilename[n++] = 0xC0 | ( utf16_ch & 0x3F);
#else // Encode as '_'
longFilename[n++] = '_';
#endif
}
if (0 == utf16_ch) break; // End of filename
} // idx
} // longFilename
#endif
2020-11-12 22:26:49 -06:00
return n;
} // DIR_IS_FILE_OR_SUBDIR
2011-11-18 15:17:37 -06:00
}
}
2011-11-18 15:17:37 -06:00
// Read next directory entry into the cache
// Assumes file is correctly positioned
dir_t* SdBaseFile::readDirCache() {
uint8_t i;
// error if not directory
2017-11-15 00:06:20 -06:00
if (!isDir()) return 0;
2011-11-18 15:17:37 -06:00
// index of entry in cache
2017-12-15 15:17:52 -06:00
i = (curPosition_ >> 5) & 0xF;
2011-11-18 15:17:37 -06:00
// use read to locate and cache block
2017-11-15 00:06:20 -06:00
if (read() < 0) return 0;
2011-11-18 15:17:37 -06:00
// advance to next entry
curPosition_ += 31;
// return pointer to entry
return vol_->cache()->dir + i;
}
2017-11-15 00:06:20 -06:00
/**
* Remove a file.
2011-11-18 15:17:37 -06:00
*
* The directory entry and all data for the file are deleted.
*
* \note This function should not be used to delete the 8.3 version of a
* file that has a long name. For example if a file has the long name
* "New Text Document.txt" you should not delete the 8.3 name "NEWTEX~1.TXT".
*
2017-11-15 00:06:20 -06:00
* \return true for success, false for failure.
2011-11-18 15:17:37 -06:00
* Reasons for failure include the file read-only, is a directory,
* or an I/O error occurred.
*/
bool SdBaseFile::remove() {
2020-05-30 23:59:29 -05:00
if (ENABLED(SDCARD_READONLY)) return false;
2011-11-18 15:17:37 -06:00
dir_t* d;
// free any clusters - will fail if read-only or directory
2017-11-15 00:06:20 -06:00
if (!truncate(0)) return false;
2011-11-18 15:17:37 -06:00
// cache directory entry
d = cacheDirEntry(SdVolume::CACHE_FOR_WRITE);
2017-11-15 00:06:20 -06:00
if (!d) return false;
2011-11-18 15:17:37 -06:00
// mark entry deleted
d->name[0] = DIR_NAME_DELETED;
// set this file closed
type_ = FAT_FILE_TYPE_CLOSED;
// write entry to SD
return vol_->cacheFlush();
return true;
}
2017-11-15 00:06:20 -06:00
/**
* Remove a file.
2011-11-18 15:17:37 -06:00
*
* The directory entry and all data for the file are deleted.
*
* \param[in] dirFile The directory that contains the file.
* \param[in] path Path for the file to be removed.
*
* \note This function should not be used to delete the 8.3 version of a
* file that has a long name. For example if a file has the long name
* "New Text Document.txt" you should not delete the 8.3 name "NEWTEX~1.TXT".
*
2017-11-15 00:06:20 -06:00
* \return true for success, false for failure.
2011-11-18 15:17:37 -06:00
* Reasons for failure include the file is a directory, is read only,
* \a dirFile is not a directory, \a path is not found
* or an I/O error occurred.
*/
bool SdBaseFile::remove(SdBaseFile* dirFile, const char* path) {
2020-05-30 23:59:29 -05:00
if (ENABLED(SDCARD_READONLY)) return false;
2011-11-18 15:17:37 -06:00
SdBaseFile file;
2017-11-15 00:06:20 -06:00
return file.open(dirFile, path, O_WRITE) ? file.remove() : false;
2011-11-18 15:17:37 -06:00
}
2017-11-15 00:06:20 -06:00
/**
* Rename a file or subdirectory.
2011-11-18 15:17:37 -06:00
*
* \param[in] dirFile Directory for the new path.
* \param[in] newPath New path name for the file/directory.
*
2017-11-15 00:06:20 -06:00
* \return true for success, false for failure.
2011-11-18 15:17:37 -06:00
* Reasons for failure include \a dirFile is not open or is not a directory
* file, newPath is invalid or already exists, or an I/O error occurs.
*/
bool SdBaseFile::rename(SdBaseFile* dirFile, const char* newPath) {
2020-05-30 23:59:29 -05:00
if (ENABLED(SDCARD_READONLY)) return false;
2011-11-18 15:17:37 -06:00
dir_t entry;
uint32_t dirCluster = 0;
SdBaseFile file;
dir_t* d;
// must be an open file or subdirectory
2017-11-15 00:06:20 -06:00
if (!(isFile() || isSubDir())) return false;
2011-11-18 15:17:37 -06:00
// can't move file
2017-11-15 00:06:20 -06:00
if (vol_ != dirFile->vol_) return false;
2011-11-18 15:17:37 -06:00
// sync() and cache directory entry
sync();
d = cacheDirEntry(SdVolume::CACHE_FOR_WRITE);
2017-11-15 00:06:20 -06:00
if (!d) return false;
2011-11-18 15:17:37 -06:00
// save directory entry
memcpy(&entry, d, sizeof(entry));
// mark entry deleted
d->name[0] = DIR_NAME_DELETED;
// make directory entry for new path
if (isFile()) {
if (!file.open(dirFile, newPath, O_CREAT | O_EXCL | O_WRITE)) {
goto restore;
}
}
else {
2011-11-18 15:17:37 -06:00
// don't create missing path prefix components
if (!file.mkdir(dirFile, newPath, false)) {
goto restore;
}
// save cluster containing new dot dot
dirCluster = file.firstCluster_;
}
// change to new directory entry
dirBlock_ = file.dirBlock_;
dirIndex_ = file.dirIndex_;
// mark closed to avoid possible destructor close call
file.type_ = FAT_FILE_TYPE_CLOSED;
// cache new directory entry
d = cacheDirEntry(SdVolume::CACHE_FOR_WRITE);
2017-11-15 00:06:20 -06:00
if (!d) return false;
2011-11-18 15:17:37 -06:00
// copy all but name field to new directory entry
memcpy(&d->attributes, &entry.attributes, sizeof(entry) - sizeof(d->name));
// update dot dot if directory
if (dirCluster) {
// get new dot dot
uint32_t block = vol_->clusterStartBlock(dirCluster);
2017-11-15 00:06:20 -06:00
if (!vol_->cacheRawBlock(block, SdVolume::CACHE_FOR_READ)) return false;
2011-11-18 15:17:37 -06:00
memcpy(&entry, &vol_->cache()->dir[1], sizeof(entry));
// free unused cluster
2017-11-15 00:06:20 -06:00
if (!vol_->freeChain(dirCluster)) return false;
2011-11-18 15:17:37 -06:00
// store new dot dot
block = vol_->clusterStartBlock(firstCluster_);
2017-11-15 00:06:20 -06:00
if (!vol_->cacheRawBlock(block, SdVolume::CACHE_FOR_WRITE)) return false;
2011-11-18 15:17:37 -06:00
memcpy(&vol_->cache()->dir[1], &entry, sizeof(entry));
}
return vol_->cacheFlush();
restore:
2017-11-15 00:06:20 -06:00
if ((d = cacheDirEntry(SdVolume::CACHE_FOR_WRITE))) {
// restore entry
d->name[0] = entry.name[0];
vol_->cacheFlush();
}
2011-11-18 15:17:37 -06:00
return false;
}
2017-11-15 00:06:20 -06:00
/**
* Remove a directory file.
2011-11-18 15:17:37 -06:00
*
* The directory file will be removed only if it is empty and is not the
* root directory. rmdir() follows DOS and Windows and ignores the
* read-only attribute for the directory.
*
* \note This function should not be used to delete the 8.3 version of a
* directory that has a long name. For example if a directory has the
* long name "New folder" you should not delete the 8.3 name "NEWFOL~1".
*
2017-11-15 00:06:20 -06:00
* \return true for success, false for failure.
2011-11-18 15:17:37 -06:00
* Reasons for failure include the file is not a directory, is the root
* directory, is not empty, or an I/O error occurred.
*/
bool SdBaseFile::rmdir() {
2020-05-30 23:59:29 -05:00
if (ENABLED(SDCARD_READONLY)) return false;
2011-11-18 15:17:37 -06:00
// must be open subdirectory
2017-11-15 00:06:20 -06:00
if (!isSubDir()) return false;
2011-11-18 15:17:37 -06:00
rewind();
// make sure directory is empty
while (curPosition_ < fileSize_) {
dir_t* p = readDirCache();
2017-11-15 00:06:20 -06:00
if (!p) return false;
2011-11-18 15:17:37 -06:00
// done if past last used entry
if (p->name[0] == DIR_NAME_FREE) break;
// skip empty slot, '.' or '..'
if (p->name[0] == DIR_NAME_DELETED || p->name[0] == '.') continue;
// error not empty
2017-11-15 00:06:20 -06:00
if (DIR_IS_FILE_OR_SUBDIR(p)) return false;
2011-11-18 15:17:37 -06:00
}
// convert empty directory to normal file for remove
type_ = FAT_FILE_TYPE_NORMAL;
flags_ |= O_WRITE;
return remove();
}
2017-11-15 00:06:20 -06:00
/**
* Recursively delete a directory and all contained files.
2011-11-18 15:17:37 -06:00
*
* This is like the Unix/Linux 'rm -rf *' if called with the root directory
* hence the name.
*
* Warning - This will remove all contents of the directory including
* subdirectories. The directory will then be removed if it is not root.
* The read-only attribute for files will be ignored.
*
* \note This function should not be used to delete the 8.3 version of
* a directory that has a long name. See remove() and rmdir().
*
2017-11-15 00:06:20 -06:00
* \return true for success, false for failure.
2011-11-18 15:17:37 -06:00
*/
bool SdBaseFile::rmRfStar() {
2020-05-30 23:59:29 -05:00
if (ENABLED(SDCARD_READONLY)) return false;
2017-09-30 16:06:43 -05:00
uint32_t index;
2011-11-18 15:17:37 -06:00
SdBaseFile f;
rewind();
while (curPosition_ < fileSize_) {
// remember position
index = curPosition_ / 32;
2011-11-18 15:17:37 -06:00
dir_t* p = readDirCache();
2017-11-15 00:06:20 -06:00
if (!p) return false;
2011-11-18 15:17:37 -06:00
// done if past last entry
if (p->name[0] == DIR_NAME_FREE) break;
// skip empty slot or '.' or '..'
if (p->name[0] == DIR_NAME_DELETED || p->name[0] == '.') continue;
// skip if part of long file name or volume label in root
if (!DIR_IS_FILE_OR_SUBDIR(p)) continue;
2017-11-15 00:06:20 -06:00
if (!f.open(this, index, O_READ)) return false;
2011-11-18 15:17:37 -06:00
if (f.isSubDir()) {
// recursively delete
2017-11-15 00:06:20 -06:00
if (!f.rmRfStar()) return false;
}
else {
2011-11-18 15:17:37 -06:00
// ignore read-only
f.flags_ |= O_WRITE;
2017-11-15 00:06:20 -06:00
if (!f.remove()) return false;
2011-11-18 15:17:37 -06:00
}
// position to next entry if required
if (curPosition_ != (32 * (index + 1))) {
2017-11-15 00:06:20 -06:00
if (!seekSet(32 * (index + 1))) return false;
2011-11-18 15:17:37 -06:00
}
}
// don't try to delete root
if (!isRoot()) {
2017-11-15 00:06:20 -06:00
if (!rmdir()) return false;
2011-11-18 15:17:37 -06:00
}
return true;
}
2017-11-15 00:06:20 -06:00
/**
* Create a file object and open it in the current working directory.
2011-11-18 15:17:37 -06:00
*
* \param[in] path A path with a valid 8.3 DOS name for a file to be opened.
*
* \param[in] oflag Values for \a oflag are constructed by a bitwise-inclusive
* OR of open flags. see SdBaseFile::open(SdBaseFile*, const char*, uint8_t).
*/
SdBaseFile::SdBaseFile(const char* path, uint8_t oflag) {
type_ = FAT_FILE_TYPE_CLOSED;
writeError = false;
open(path, oflag);
}
2017-11-15 00:06:20 -06:00
/**
* Sets a file's position.
2011-11-18 15:17:37 -06:00
*
* \param[in] pos The new position in bytes from the beginning of the file.
*
2017-11-15 00:06:20 -06:00
* \return true for success, false for failure.
2011-11-18 15:17:37 -06:00
*/
2017-11-15 00:06:20 -06:00
bool SdBaseFile::seekSet(const uint32_t pos) {
uint32_t nCur, nNew;
2011-11-18 15:17:37 -06:00
// error if file not open or seek past end of file
2017-11-15 00:06:20 -06:00
if (!isOpen() || pos > fileSize_) return false;
2011-11-18 15:17:37 -06:00
if (type_ == FAT_FILE_TYPE_ROOT_FIXED) {
curPosition_ = pos;
2017-11-15 00:06:20 -06:00
return true;
2011-11-18 15:17:37 -06:00
}
if (pos == 0) {
2017-11-15 00:06:20 -06:00
curCluster_ = curPosition_ = 0; // set position to start of file
return true;
2011-11-18 15:17:37 -06:00
}
2017-11-15 00:06:20 -06:00
2011-11-18 15:17:37 -06:00
// calculate cluster index for cur and new position
nCur = (curPosition_ - 1) >> (vol_->clusterSizeShift_ + 9);
nNew = (pos - 1) >> (vol_->clusterSizeShift_ + 9);
2017-11-15 00:06:20 -06:00
if (nNew < nCur || curPosition_ == 0)
curCluster_ = firstCluster_; // must follow chain from first cluster
else
nNew -= nCur; // advance from curPosition
2011-11-18 15:17:37 -06:00
2017-11-15 00:06:20 -06:00
while (nNew--)
if (!vol_->fatGet(curCluster_, &curCluster_)) return false;
2011-11-18 15:17:37 -06:00
2017-11-15 00:06:20 -06:00
curPosition_ = pos;
return true;
2011-11-18 15:17:37 -06:00
}
2017-11-15 00:06:20 -06:00
2016-02-10 22:49:25 -06:00
void SdBaseFile::setpos(filepos_t* pos) {
2011-11-18 15:17:37 -06:00
curPosition_ = pos->position;
curCluster_ = pos->cluster;
}
2017-11-15 00:06:20 -06:00
/**
* The sync() call causes all modified data and directory fields
2011-11-18 15:17:37 -06:00
* to be written to the storage device.
*
2017-11-15 00:06:20 -06:00
* \return true for success, false for failure.
2011-11-18 15:17:37 -06:00
* Reasons for failure include a call to sync() before a file has been
* opened or an I/O error.
*/
bool SdBaseFile::sync() {
// only allow open files and directories
2020-05-30 23:59:29 -05:00
if (ENABLED(SDCARD_READONLY) || !isOpen()) goto FAIL;
2011-11-18 15:17:37 -06:00
if (flags_ & F_FILE_DIR_DIRTY) {
dir_t* d = cacheDirEntry(SdVolume::CACHE_FOR_WRITE);
// check for deleted by another open file object
2017-08-11 15:55:07 -05:00
if (!d || d->name[0] == DIR_NAME_DELETED) goto FAIL;
2011-11-18 15:17:37 -06:00
// do not set filesize for dir files
if (!isDir()) d->fileSize = fileSize_;
// update first cluster fields
2017-08-09 13:23:14 -05:00
d->firstClusterLow = firstCluster_ & 0xFFFF;
2011-11-18 15:17:37 -06:00
d->firstClusterHigh = firstCluster_ >> 16;
// set modify time if user supplied a callback date/time function
if (dateTime_) {
dateTime_(&d->lastWriteDate, &d->lastWriteTime);
d->lastAccessDate = d->lastWriteDate;
}
// clear directory dirty
flags_ &= ~F_FILE_DIR_DIRTY;
}
return vol_->cacheFlush();
2017-08-11 15:55:07 -05:00
FAIL:
2011-11-18 15:17:37 -06:00
writeError = true;
return false;
}
2017-11-15 00:06:20 -06:00
/**
* Copy a file's timestamps
2011-11-18 15:17:37 -06:00
*
* \param[in] file File to copy timestamps from.
*
* \note
* Modify and access timestamps may be overwritten if a date time callback
* function has been set by dateTimeCallback().
*
2017-11-15 00:06:20 -06:00
* \return true for success, false for failure.
2011-11-18 15:17:37 -06:00
*/
bool SdBaseFile::timestamp(SdBaseFile* file) {
dir_t* d;
dir_t dir;
// get timestamps
2017-11-15 00:06:20 -06:00
if (!file->dirEntry(&dir)) return false;
2011-11-18 15:17:37 -06:00
// update directory fields
2017-11-15 00:06:20 -06:00
if (!sync()) return false;
2011-11-18 15:17:37 -06:00
d = cacheDirEntry(SdVolume::CACHE_FOR_WRITE);
2017-11-15 00:06:20 -06:00
if (!d) return false;
2011-11-18 15:17:37 -06:00
// copy timestamps
d->lastAccessDate = dir.lastAccessDate;
d->creationDate = dir.creationDate;
d->creationTime = dir.creationTime;
d->creationTimeTenths = dir.creationTimeTenths;
d->lastWriteDate = dir.lastWriteDate;
d->lastWriteTime = dir.lastWriteTime;
// write back entry
return vol_->cacheFlush();
}
2017-11-15 00:06:20 -06:00
/**
* Set a file's timestamps in its directory entry.
2011-11-18 15:17:37 -06:00
*
* \param[in] flags Values for \a flags are constructed by a bitwise-inclusive
* OR of flags from the following list
*
* T_ACCESS - Set the file's last access date.
*
* T_CREATE - Set the file's creation date and time.
*
* T_WRITE - Set the file's last write/modification date and time.
*
* \param[in] year Valid range 1980 - 2107 inclusive.
*
* \param[in] month Valid range 1 - 12 inclusive.
*
* \param[in] day Valid range 1 - 31 inclusive.
*
* \param[in] hour Valid range 0 - 23 inclusive.
*
* \param[in] minute Valid range 0 - 59 inclusive.
*
* \param[in] second Valid range 0 - 59 inclusive
*
* \note It is possible to set an invalid date since there is no check for
* the number of days in a month.
*
* \note
* Modify and access timestamps may be overwritten if a date time callback
* function has been set by dateTimeCallback().
*
2017-11-15 00:06:20 -06:00
* \return true for success, false for failure.
2011-11-18 15:17:37 -06:00
*/
bool SdBaseFile::timestamp(uint8_t flags, uint16_t year, uint8_t month,
uint8_t day, uint8_t hour, uint8_t minute, uint8_t second) {
2020-05-30 23:59:29 -05:00
if (ENABLED(SDCARD_READONLY)) return false;
2017-11-15 00:06:20 -06:00
uint16_t dirDate, dirTime;
2011-11-18 15:17:37 -06:00
dir_t* d;
if (!isOpen()
|| year < 1980
|| year > 2107
|| month < 1
|| month > 12
|| day < 1
|| day > 31
|| hour > 23
|| minute > 59
|| second > 59) {
2017-11-15 00:06:20 -06:00
return false;
2011-11-18 15:17:37 -06:00
}
// update directory entry
2017-11-15 00:06:20 -06:00
if (!sync()) return false;
2011-11-18 15:17:37 -06:00
d = cacheDirEntry(SdVolume::CACHE_FOR_WRITE);
2017-11-15 00:06:20 -06:00
if (!d) return false;
2011-11-18 15:17:37 -06:00
dirDate = FAT_DATE(year, month, day);
dirTime = FAT_TIME(hour, minute, second);
if (flags & T_ACCESS) {
d->lastAccessDate = dirDate;
}
if (flags & T_CREATE) {
d->creationDate = dirDate;
d->creationTime = dirTime;
// seems to be units of 1/100 second not 1/10 as Microsoft states
d->creationTimeTenths = second & 1 ? 100 : 0;
}
if (flags & T_WRITE) {
d->lastWriteDate = dirDate;
d->lastWriteTime = dirTime;
}
return vol_->cacheFlush();
}
2017-11-15 00:06:20 -06:00
/**
* Truncate a file to a specified length. The current file position
2011-11-18 15:17:37 -06:00
* will be maintained if it is less than or equal to \a length otherwise
* it will be set to end of file.
*
* \param[in] length The desired length for the file.
*
2017-11-15 00:06:20 -06:00
* \return true for success, false for failure.
2011-11-18 15:17:37 -06:00
* Reasons for failure include file is read only, file is a directory,
* \a length is greater than the current file size or an I/O error occurs.
*/
bool SdBaseFile::truncate(uint32_t length) {
2020-05-30 23:59:29 -05:00
if (ENABLED(SDCARD_READONLY)) return false;
2011-11-18 15:17:37 -06:00
uint32_t newPos;
// error if not a normal file or read-only
2017-11-15 00:06:20 -06:00
if (!isFile() || !(flags_ & O_WRITE)) return false;
2011-11-18 15:17:37 -06:00
// error if length is greater than current size
2017-11-15 00:06:20 -06:00
if (length > fileSize_) return false;
2011-11-18 15:17:37 -06:00
// fileSize and length are zero - nothing to do
if (fileSize_ == 0) return true;
// remember position for seek after truncation
newPos = curPosition_ > length ? length : curPosition_;
// position to last cluster in truncated file
2017-11-15 00:06:20 -06:00
if (!seekSet(length)) return false;
2011-11-18 15:17:37 -06:00
if (length == 0) {
// free all clusters
2017-11-15 00:06:20 -06:00
if (!vol_->freeChain(firstCluster_)) return false;
2011-11-18 15:17:37 -06:00
firstCluster_ = 0;
}
else {
2011-11-18 15:17:37 -06:00
uint32_t toFree;
2017-11-15 00:06:20 -06:00
if (!vol_->fatGet(curCluster_, &toFree)) return false;
2011-11-18 15:17:37 -06:00
if (!vol_->isEOC(toFree)) {
// free extra clusters
2017-11-15 00:06:20 -06:00
if (!vol_->freeChain(toFree)) return false;
2011-11-18 15:17:37 -06:00
// current cluster is end of chain
2017-11-15 00:06:20 -06:00
if (!vol_->fatPutEOC(curCluster_)) return false;
2011-11-18 15:17:37 -06:00
}
}
fileSize_ = length;
// need to update directory entry
flags_ |= F_FILE_DIR_DIRTY;
2017-11-15 00:06:20 -06:00
if (!sync()) return false;
2011-11-18 15:17:37 -06:00
// set file to correct position
return seekSet(newPos);
}
2017-11-15 00:06:20 -06:00
/**
* Write data to an open file.
2011-11-18 15:17:37 -06:00
*
* \note Data is moved to the cache but may not be written to the
* storage device until sync() is called.
*
* \param[in] buf Pointer to the location of the data to be written.
*
* \param[in] nbyte Number of bytes to write.
*
* \return For success write() returns the number of bytes written, always
* \a nbyte. If an error occurs, write() returns -1. Possible errors
* include write() is called before a file has been opened, write is called
* for a read-only file, device is full, a corrupt file system or an I/O error.
*/
int16_t SdBaseFile::write(const void* buf, uint16_t nbyte) {
2020-05-30 23:59:29 -05:00
#if ENABLED(SDCARD_READONLY)
writeError = true; return -1;
#endif
2011-11-18 15:17:37 -06:00
// convert void* to uint8_t* - must be before goto statements
const uint8_t* src = reinterpret_cast<const uint8_t*>(buf);
// number of bytes left to write - must be before goto statements
uint16_t nToWrite = nbyte;
// error if not a normal file or is read-only
2017-08-11 15:55:07 -05:00
if (!isFile() || !(flags_ & O_WRITE)) goto FAIL;
2011-11-18 15:17:37 -06:00
// seek to end of file if append flag
if ((flags_ & O_APPEND) && curPosition_ != fileSize_) {
2017-08-11 15:55:07 -05:00
if (!seekEnd()) goto FAIL;
2011-11-18 15:17:37 -06:00
}
while (nToWrite > 0) {
uint8_t blockOfCluster = vol_->blockOfCluster(curPosition_);
2017-08-09 13:23:14 -05:00
uint16_t blockOffset = curPosition_ & 0x1FF;
2011-11-18 15:17:37 -06:00
if (blockOfCluster == 0 && blockOffset == 0) {
// start of new cluster
if (curCluster_ == 0) {
if (firstCluster_ == 0) {
// allocate first cluster of file
2017-08-11 15:55:07 -05:00
if (!addCluster()) goto FAIL;
}
else {
2011-11-18 15:17:37 -06:00
curCluster_ = firstCluster_;
}
}
else {
2011-11-18 15:17:37 -06:00
uint32_t next;
2017-08-11 15:55:07 -05:00
if (!vol_->fatGet(curCluster_, &next)) goto FAIL;
2011-11-18 15:17:37 -06:00
if (vol_->isEOC(next)) {
// add cluster if at end of chain
2017-08-11 15:55:07 -05:00
if (!addCluster()) goto FAIL;
}
else {
2011-11-18 15:17:37 -06:00
curCluster_ = next;
}
}
}
// max space in block
uint16_t n = 512 - blockOffset;
// lesser of space and amount to write
NOMORE(n, nToWrite);
2011-11-18 15:17:37 -06:00
// block for data write
uint32_t block = vol_->clusterStartBlock(curCluster_) + blockOfCluster;
if (n == 512) {
// full block - don't need to use cache
if (vol_->cacheBlockNumber() == block) {
// invalidate cache if block is in cache
2017-08-09 13:23:14 -05:00
vol_->cacheSetBlockNumber(0xFFFFFFFF, false);
2011-11-18 15:17:37 -06:00
}
2017-08-11 15:55:07 -05:00
if (!vol_->writeBlock(block, src)) goto FAIL;
}
else {
2011-11-18 15:17:37 -06:00
if (blockOffset == 0 && curPosition_ >= fileSize_) {
// start of new block don't need to read into cache
2017-08-11 15:55:07 -05:00
if (!vol_->cacheFlush()) goto FAIL;
2011-11-18 15:17:37 -06:00
// set cache dirty and SD address of block
vol_->cacheSetBlockNumber(block, true);
}
else {
2011-11-18 15:17:37 -06:00
// rewrite part of block
2017-08-11 15:55:07 -05:00
if (!vol_->cacheRawBlock(block, SdVolume::CACHE_FOR_WRITE)) goto FAIL;
2011-11-18 15:17:37 -06:00
}
uint8_t* dst = vol_->cache()->data + blockOffset;
memcpy(dst, src, n);
}
curPosition_ += n;
src += n;
nToWrite -= n;
}
if (curPosition_ > fileSize_) {
// update fileSize and insure sync will update dir entry
fileSize_ = curPosition_;
flags_ |= F_FILE_DIR_DIRTY;
}
else if (dateTime_ && nbyte) {
2011-11-18 15:17:37 -06:00
// insure sync will update modified date and time
flags_ |= F_FILE_DIR_DIRTY;
}
if (flags_ & O_SYNC) {
2017-08-11 15:55:07 -05:00
if (!sync()) goto FAIL;
2011-11-18 15:17:37 -06:00
}
return nbyte;
2017-08-11 15:55:07 -05:00
FAIL:
2011-11-18 15:17:37 -06:00
// return for write error
writeError = true;
return -1;
}
2017-11-15 00:06:20 -06:00
2017-09-06 06:28:32 -05:00
#endif // SDSUPPORT