Skip to content

Commit ae17f6e

Browse files
committed
Add FileHandle::truncate and ftruncate
Add support for file truncation (or extension) to the abstract API. No hooks to actual implementations in this commit.
1 parent ff7a316 commit ae17f6e

File tree

3 files changed

+33
-0
lines changed

3 files changed

+33
-0
lines changed

platform/FileHandle.h

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -138,6 +138,21 @@ class FileHandle : private NonCopyable<FileHandle> {
138138
*/
139139
virtual off_t size();
140140

141+
/** Truncate or extend a file.
142+
*
143+
* The file's length is set to the specified value. The seek pointer is
144+
* not changed. If the file is extended, the extended area appears as if
145+
* it were zero-filled.
146+
*
147+
* @param length The requested new length for the file
148+
*
149+
* @return Zero on success, negative error code on failure
150+
*/
151+
virtual int truncate(off_t length)
152+
{
153+
return -EINVAL;
154+
}
155+
141156
/** Move the file position to a given offset from a given location.
142157
*
143158
* @param offset The offset from whence to move to

platform/mbed_retarget.cpp

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -842,6 +842,23 @@ extern "C" off_t lseek(int fildes, off_t offset, int whence)
842842
return off;
843843
}
844844

845+
extern "C" int ftruncate(int fildes, off_t length)
846+
{
847+
FileHandle *fhc = get_fhc(fildes);
848+
if (fhc == NULL) {
849+
errno = EBADF;
850+
return -1;
851+
}
852+
853+
int err = fhc->truncate(length);
854+
if (err < 0) {
855+
errno = -err;
856+
return -1;
857+
} else {
858+
return 0;
859+
}
860+
}
861+
845862
#ifdef __ARMCC_VERSION
846863
extern "C" int PREFIX(_ensure)(FILEHANDLE fh)
847864
{

platform/mbed_retarget.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -524,6 +524,7 @@ extern "C" {
524524
ssize_t write(int fildes, const void *buf, size_t nbyte);
525525
ssize_t read(int fildes, void *buf, size_t nbyte);
526526
off_t lseek(int fildes, off_t offset, int whence);
527+
int ftruncate(int fildes, off_t length);
527528
int isatty(int fildes);
528529
int fsync(int fildes);
529530
int fstat(int fildes, struct stat *st);

0 commit comments

Comments
 (0)