From 2b45488ae024286da526fe770b982277e5335551 Mon Sep 17 00:00:00 2001 From: Felix Fietkau Date: Mon, 17 Jun 2024 11:12:43 +0200 Subject: [PATCH] fs: add ftruncate() function Trunates the file referenced by a file descriptor Signed-off-by: Felix Fietkau --- lib/fs.c | 41 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) diff --git a/lib/fs.c b/lib/fs.c index 4d9695e3..7e3ad331 100644 --- a/lib/fs.c +++ b/lib/fs.c @@ -738,6 +738,46 @@ uc_fs_seek(uc_vm_t *vm, size_t nargs) return ucv_boolean_new(true); } +/** + * Truncate file to a given size + * + * Returns `true` if the file was successfully truncated. + * + * Returns `null` if an error occurred. + * + * @function module:fs.file#truncate + * + * @param {number} [fd] + * The file descriptor. + * + * @param {number} [offset=0] + * The offset in bytes. + * + * @returns {?boolean} + */ +static uc_value_t * +uc_fs_ftruncate(uc_vm_t *vm, size_t nargs) +{ + uc_value_t *fd = uc_fn_arg(0); + uc_value_t *ofs = uc_fn_arg(1); + off_t offset; + + if (ucv_type(fd) != UC_INTEGER) + err_return(EINVAL); + + if (!ofs) + offset = 0; + else if (ucv_type(ofs) != UC_INTEGER) + err_return(EINVAL); + else + offset = (off_t)ucv_int64_get(ofs); + + if (ftruncate(ucv_int64_get(fd), offset) < 0) + err_return(errno); + + return ucv_boolean_new(true); +} + /** * Obtain current read position. * @@ -2609,6 +2649,7 @@ static const uc_function_list_t global_fns[] = { { "writefile", uc_fs_writefile }, { "realpath", uc_fs_realpath }, { "pipe", uc_fs_pipe }, + { "ftruncate", uc_fs_ftruncate }, };