* Truncate a file to a specified length. The current file position * 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. * * \return true for success, false for failure. * Reasons for failure include file is read only, file is a directory, * \a length is greater than the current file
| 2108 | * \a length is greater than the current file size or an I/O error occurs. |
| 2109 | */ |
| 2110 | bool SdBaseFile::truncate(uint32_t length) { |
| 2111 | if (ENABLED(SDCARD_READONLY)) return false; |
| 2112 | |
| 2113 | uint32_t newPos; |
| 2114 | // error if not a normal file or read-only |
| 2115 | if (!isFile() || !(flags_ & O_WRITE)) return false; |
| 2116 | |
| 2117 | // error if length is greater than current size |
| 2118 | if (length > fileSize_) return false; |
| 2119 | |
| 2120 | // fileSize and length are zero - nothing to do |
| 2121 | if (fileSize_ == 0) return true; |
| 2122 | |
| 2123 | // remember position for seek after truncation |
| 2124 | newPos = curPosition_ > length ? length : curPosition_; |
| 2125 | |
| 2126 | // position to last cluster in truncated file |
| 2127 | if (!seekSet(length)) return false; |
| 2128 | |
| 2129 | if (length == 0) { |
| 2130 | // free all clusters |
| 2131 | if (!vol_->freeChain(firstCluster_)) return false; |
| 2132 | firstCluster_ = 0; |
| 2133 | } |
| 2134 | else { |
| 2135 | uint32_t toFree; |
| 2136 | if (!vol_->fatGet(curCluster_, &toFree)) return false; |
| 2137 | |
| 2138 | if (!vol_->isEOC(toFree)) { |
| 2139 | // free extra clusters |
| 2140 | if (!vol_->freeChain(toFree)) return false; |
| 2141 | |
| 2142 | // current cluster is end of chain |
| 2143 | if (!vol_->fatPutEOC(curCluster_)) return false; |
| 2144 | } |
| 2145 | } |
| 2146 | fileSize_ = length; |
| 2147 | |
| 2148 | // need to update directory entry |
| 2149 | flags_ |= F_FILE_DIR_DIRTY; |
| 2150 | |
| 2151 | if (!sync()) return false; |
| 2152 | |
| 2153 | // set file to correct position |
| 2154 | return seekSet(newPos); |
| 2155 | } |
| 2156 | |
| 2157 | /** |
| 2158 | * Write data to an open file. |