Skip to content

Commit f64fdd5

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 5b25b66 commit f64fdd5

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
@@ -137,6 +137,21 @@ class FileHandle : private NonCopyable<FileHandle> {
137137
*/
138138
virtual off_t size();
139139

140+
/** Truncate or extend a file.
141+
*
142+
* The file's length is set to the specified value. The seek pointer is
143+
* not changed. If the file is extended, the extended area appears as if
144+
* it were zero-filled.
145+
*
146+
* @param length The requested new length for the file
147+
*
148+
* @return Zero on success, negative error code on failure
149+
*/
150+
virtual int truncate(off_t length)
151+
{
152+
return -EINVAL;
153+
}
154+
140155
/** Move the file position to a given offset from a given location.
141156
*
142157
* @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
@@ -841,6 +841,23 @@ extern "C" off_t lseek(int fildes, off_t offset, int whence)
841841
return off;
842842
}
843843

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

platform/mbed_retarget.h

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

0 commit comments

Comments
 (0)