]> pd.if.org Git - pdclib/blob - functions/stdio/ftell.c
PDCLIB-7: Add _PDCLIB_ftell64 to give us full precision file positioning information...
[pdclib] / functions / stdio / ftell.c
1 /* $Id$ */
2
3 /* ftell( FILE * )
4
5    This file is part of the Public Domain C Library (PDCLib).
6    Permission is granted to use, modify, and / or redistribute at will.
7 */
8
9 #include <stdio.h>
10 #include <stdint.h>
11 #include <limits.h>
12 #include <errno.h>
13
14 #ifndef REGTEST
15
16 long int ftell( struct _PDCLIB_file_t * stream )
17 {
18     uint_fast64_t off64 = _PDCLIB_ftell64( stream );
19
20     if ( off64 > LONG_MAX )
21     {
22         /* integer overflow */
23         errno = ERANGE;
24         return -1;
25     }
26     return off64;
27 }
28
29 #endif
30
31 #ifdef TEST
32 #include <_PDCLIB_test.h>
33
34 #include <stdlib.h>
35
36 int main( void )
37 {
38     /* Testing all the basic I/O functions individually would result in lots
39        of duplicated code, so I took the liberty of lumping it all together
40        here.
41     */
42     /* The following functions delegate their tests to here:
43        fgetc fflush rewind fputc ungetc fseek
44        flushbuffer seek fillbuffer prepread prepwrite
45     */
46     char * buffer = (char*)malloc( 4 );
47     FILE * fh;
48     TESTCASE( ( fh = tmpfile() ) != NULL );
49     TESTCASE( setvbuf( fh, buffer, _IOLBF, 4 ) == 0 );
50     /* Testing ungetc() at offset 0 */
51     rewind( fh );
52     TESTCASE( ungetc( 'x', fh ) == 'x' );
53     TESTCASE( ftell( fh ) == -1l );
54     rewind( fh );
55     TESTCASE( ftell( fh ) == 0l );
56     /* Commence "normal" tests */
57     TESTCASE( fputc( '1', fh ) == '1' );
58     TESTCASE( fputc( '2', fh ) == '2' );
59     TESTCASE( fputc( '3', fh ) == '3' );
60     /* Positions incrementing as expected? */
61     TESTCASE( ftell( fh ) == 3l );
62     TESTCASE_NOREG( fh->pos.offset == 0l );
63     TESTCASE_NOREG( fh->bufidx == 3l );
64     /* Buffer properly flushed when full? */
65     TESTCASE( fputc( '4', fh ) == '4' );
66     TESTCASE_NOREG( fh->pos.offset == 4l );
67     TESTCASE_NOREG( fh->bufidx == 0 );
68     /* fflush() resetting positions as expected? */
69     TESTCASE( fputc( '5', fh ) == '5' );
70     TESTCASE( fflush( fh ) == 0 );
71     TESTCASE( ftell( fh ) == 5l );
72     TESTCASE_NOREG( fh->pos.offset == 5l );
73     TESTCASE_NOREG( fh->bufidx == 0l );
74     /* rewind() resetting positions as expected? */
75     rewind( fh );
76     TESTCASE( ftell( fh ) == 0l );
77     TESTCASE_NOREG( fh->pos.offset == 0 );
78     TESTCASE_NOREG( fh->bufidx == 0 );
79     /* Reading back first character after rewind for basic read check */
80     TESTCASE( fgetc( fh ) == '1' );
81     /* TODO: t.b.c. */
82     TESTCASE( fclose( fh ) == 0 );
83     return TEST_RESULTS;
84 }
85
86 #endif
87