evil: Implement ftruncate

Create POSIX-compliant ftruncate with tests.
This commit is contained in:
Cauê Baasch de Souza 2020-06-30 22:24:25 -03:00 committed by Felipe Magno de Almeida
parent 38a94040a2
commit edb195cfd2
3 changed files with 54 additions and 0 deletions

View File

@ -25,6 +25,26 @@ execvp(const char *file, char *const argv[])
LONGLONG _evil_time_freq;
LONGLONG _evil_time_count;
EVIL_API int
ftruncate(int fd, off_t size)
{
HANDLE file = (HANDLE)_get_osfhandle(fd);
if (SetFilePointer(file, (LONG)size, NULL, FILE_BEGIN) == INVALID_SET_FILE_POINTER)
{
_set_errno(EINVAL);
return -1;
}
if (!SetEndOfFile(file))
{
_set_errno(EIO);
return -1;
}
return 0;
}
/*
* Time related functions
*

View File

@ -23,6 +23,7 @@
#include <process.h> // for _execvp (but not execvp), getpid
#undef execvp
EVIL_API int execvp(const char *file, char *const argv[]);
EVIL_API int ftruncate(int fd, off_t size);
/* Values for the second argument to access. These may be OR'd together. */
#define R_OK 4 /* Test for read permission. */

View File

@ -22,6 +22,8 @@
#include <stdlib.h>
#include <stdio.h>
#include <io.h>
#include <fcntl.h>
# define WIN32_LEAN_AND_MEAN
# include <winsock2.h>
@ -109,7 +111,38 @@ EFL_START_TEST(evil_unistd_pipe)
}
EFL_END_TEST
EFL_START_TEST(evil_unistd_ftruncate)
{
FILE* f = fopen("foo.txt", "wb");
ck_assert(f);
fseek(f, 0L, SEEK_END);
ck_assert_int_eq(ftell(f), 0);
int fd = fileno(f);
int ret;
ret = ftruncate(fd, 16L);
ck_assert(ret >= 0);
fseek(f, 0L, SEEK_END);
ck_assert_int_eq(ftell(f), 16);
ret = ftruncate(fd, 8L);
ck_assert(ret >= 0);
fseek(f, 0L, SEEK_END);
ck_assert_int_eq(ftell(f), 8);
ret = ftruncate(fd, -8L);
ck_assert(ret < 0);
ck_assert_int_eq(errno, EINVAL);
fseek(f, 0L, SEEK_END);
ck_assert_int_eq(ftell(f), 8);
fclose(f);
}
EFL_END_TEST
void evil_test_unistd(TCase *tc)
{
tcase_add_test(tc, evil_unistd_pipe);
tcase_add_test(tc, evil_unistd_ftruncate);
}