Skip to content

Commit

Permalink
fs: add ftruncate() function
Browse files Browse the repository at this point in the history
Trunates the file referenced by a file descriptor

Signed-off-by: Felix Fietkau <[email protected]>
  • Loading branch information
nbd168 committed Jun 17, 2024
1 parent 2a0240f commit 2b45488
Showing 1 changed file with 41 additions and 0 deletions.
41 changes: 41 additions & 0 deletions lib/fs.c
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*
Expand Down Expand Up @@ -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 },
};


Expand Down

0 comments on commit 2b45488

Please sign in to comment.