Skip to content

Commit

Permalink
tests/ansi: add ftell test case
Browse files Browse the repository at this point in the history
This patch adds a simple test for ftell's functionality which also
acts as a simple reproducible test case for the failing GMP tests
documented in managarm#1221. This test currently fails because our behaviour
when checking ftell after a ungetc doesn't match glibc.
  • Loading branch information
lzcunt committed Jan 28, 2025
1 parent 501b87c commit fe808a2
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 0 deletions.
64 changes: 64 additions & 0 deletions tests/ansi/ftell.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
#include <stdio.h>
#include <assert.h>
#include <string.h>

#ifdef USE_HOST_LIBC
#define TEST_FILE "ftell-host-libc.tmp"
#else
#define TEST_FILE "ftell.tmp"
#endif

int main() {
FILE *file;
char str[] = "mlibc ftell test";
int str_size = sizeof(str) - 1;
char buffer[20];

// Clear buffer to zero
memset(buffer, 0, sizeof(buffer));

// Open the file for writing in binary mode, because ftell is unspecified
// in text mode.
file = fopen(TEST_FILE, "wb");
assert(file);

// Write string minus null terminator, flush and close.
assert(fwrite(str, 1, str_size, file) == str_size);
fflush(file);
fclose(file);

// Open the file for reading in binary mode.
file = fopen(TEST_FILE, "rb");
assert(file);

// Check position indicator at the start of the file.
assert(ftell(file) == 0);

// Read 4 bytes and check fread and ftell.
assert(fread(buffer, 1, 4, file) == 4);
assert(ftell(file) == 4);

// Rewind and check position indicator at the start of the file.
rewind(file);
assert(ftell(file) == 0);

// Read the entire file and check fread and ftell.
assert(fread(buffer, 1, str_size, file) == str_size);
assert(ftell(file) == str_size);

// Rewind and check how ftell interacts with getc.
rewind(file);
assert(fgetc(file) == 'm');
assert(ftell(file) == 1);
assert(fgetc(file) == 'l');
assert(ftell(file) == 2);

// Check how ungetc interacts with ftell
assert(ungetc('X', file) == 'X');
int ftell_after_ungetc = ftell(file);
printf("ftell_after_ungetc: %d\n", ftell_after_ungetc);
assert(ftell_after_ungetc == 1);

fclose(file);
return 0;
}
1 change: 1 addition & 0 deletions tests/meson.build
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ all_test_cases = [
'ansi/strxfrm',
'ansi/calloc',
'ansi/fgetpos',
'ansi/ftell',
'bsd/ns_get_put',
'bsd/reallocarray',
'bsd/strl',
Expand Down

0 comments on commit fe808a2

Please sign in to comment.