diff --git a/platform/FileHandle.h b/platform/FileHandle.h index 07010df495..cbaf694e3e 100644 --- a/platform/FileHandle.h +++ b/platform/FileHandle.h @@ -138,6 +138,21 @@ public: */ virtual off_t size(); + /** Truncate or extend a file. + * + * The file's length is set to the specified value. The seek pointer is + * not changed. If the file is extended, the extended area appears as if + * it were zero-filled. + * + * @param length The requested new length for the file + * + * @return Zero on success, negative error code on failure + */ + virtual int truncate(off_t length) + { + return -EINVAL; + } + /** Move the file position to a given offset from a given location. * * @param offset The offset from whence to move to diff --git a/platform/mbed_retarget.cpp b/platform/mbed_retarget.cpp index 276701f70b..2a23757b8b 100644 --- a/platform/mbed_retarget.cpp +++ b/platform/mbed_retarget.cpp @@ -842,6 +842,23 @@ extern "C" off_t lseek(int fildes, off_t offset, int whence) return off; } +extern "C" int ftruncate(int fildes, off_t length) +{ + FileHandle *fhc = get_fhc(fildes); + if (fhc == NULL) { + errno = EBADF; + return -1; + } + + int err = fhc->truncate(length); + if (err < 0) { + errno = -err; + return -1; + } else { + return 0; + } +} + #ifdef __ARMCC_VERSION extern "C" int PREFIX(_ensure)(FILEHANDLE fh) { diff --git a/platform/mbed_retarget.h b/platform/mbed_retarget.h index 9eb27dca6a..c7a86dfe54 100644 --- a/platform/mbed_retarget.h +++ b/platform/mbed_retarget.h @@ -524,6 +524,7 @@ extern "C" { ssize_t write(int fildes, const void *buf, size_t nbyte); ssize_t read(int fildes, void *buf, size_t nbyte); off_t lseek(int fildes, off_t offset, int whence); + int ftruncate(int fildes, off_t length); int isatty(int fildes); int fsync(int fildes); int fstat(int fildes, struct stat *st);