Skip to content

Commit

Permalink
fs: add truncate() file method
Browse files Browse the repository at this point in the history
Trunates the file referenced by a file handle

Signed-off-by: Felix Fietkau <[email protected]>
  • Loading branch information
nbd168 committed Jun 17, 2024
1 parent 2a0240f commit e0bab40
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 0 deletions.
38 changes: 38 additions & 0 deletions lib/fs.c
Original file line number Diff line number Diff line change
Expand Up @@ -738,6 +738,43 @@ 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} [offset=0]
* The offset in bytes.
*
* @returns {?boolean}
*/
static uc_value_t *
uc_fs_truncate(uc_vm_t *vm, size_t nargs)
{
FILE *fp = uc_fn_thisval("fs.file");
uc_value_t *ofs = uc_fn_arg(0);
off_t offset;

if (!fp)
err_return(EBADF);

if (!ofs)
offset = 0;
else if (ucv_type(ofs) != UC_INTEGER)
err_return(EINVAL);
else
offset = (off_t)ucv_int64_get(ofs);

if (ftruncate(fileno(fp), offset) < 0)
err_return(errno);

return ucv_boolean_new(true);
}

/**
* Obtain current read position.
*
Expand Down Expand Up @@ -2571,6 +2608,7 @@ static const uc_function_list_t file_fns[] = {
{ "fileno", uc_fs_fileno },
{ "error", uc_fs_error },
{ "isatty", uc_fs_isatty },
{ "truncate", uc_fs_truncate },
};

static const uc_function_list_t dir_fns[] = {
Expand Down
1 change: 1 addition & 0 deletions tests/custom/03_stdlib/40_proto
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ When invoked with two arguments, returns the given value.
Hello, World!
[
{
"truncate": "function truncate(...) { [native code] }",
"isatty": "function isatty(...) { [native code] }",
"error": "function error(...) { [native code] }",
"fileno": "function fileno(...) { [native code] }",
Expand Down

0 comments on commit e0bab40

Please sign in to comment.