]> pd.if.org Git - pdclib/blob - functions/stdio/_PDCLIB_ftell64.c
dos2unix
[pdclib] / functions / stdio / _PDCLIB_ftell64.c
1 /* _PDCLIB_ftell64( FILE * )
2
3    This file is part of the Public Domain C Library (PDCLib).
4    Permission is granted to use, modify, and / or redistribute at will.
5 */
6
7 #include <stdio.h>
8 #include <stdint.h>
9 #include <limits.h>
10
11 #ifndef REGTEST
12 #include "_PDCLIB_io.h"
13
14 uint_fast64_t _PDCLIB_ftell64_unlocked( FILE * stream )
15 {
16     /* ftell() must take into account:
17        - the actual *physical* offset of the file, i.e. the offset as recognized
18          by the operating system (and stored in stream->pos.offset); and
19        - any buffers held by PDCLib, which
20          - in case of unwritten buffers, count in *addition* to the offset; or
21          - in case of unprocessed pre-read buffers, count in *substraction* to
22            the offset. (Remember to count ungetidx into this number.)
23        Conveniently, the calculation ( ( bufend - bufidx ) + ungetidx ) results
24        in just the right number in both cases:
25          - in case of unwritten buffers, ( ( 0 - unwritten ) + 0 )
26            i.e. unwritten bytes as negative number
27          - in case of unprocessed pre-read, ( ( preread - processed ) + unget )
28            i.e. unprocessed bytes as positive number.
29        That is how the somewhat obscure return-value calculation works.
30     */
31
32     /* ungetc on a stream at offset==0 will cause an overflow to UINT64_MAX.
33      * C99/C11 says that the return value of ftell in this case is 
34      * "indeterminate"
35      */
36
37     return ( stream->pos.offset - ( ( (int)stream->bufend - (int)stream->bufidx ) + (int)stream->ungetidx ) );
38 }
39
40 uint_fast64_t _PDCLIB_ftell64( FILE * stream )
41 {
42   _PDCLIB_flockfile( stream );
43   uint_fast64_t pos = _PDCLIB_ftell64_unlocked( stream );
44   _PDCLIB_funlockfile( stream );
45   return pos;
46 }
47
48 #endif
49
50 #ifdef TEST
51 #include "_PDCLIB_test.h"
52
53 #include <stdlib.h>
54
55 int main( void )
56 {
57     /* Tested by ftell */
58     return TEST_RESULTS;
59 }
60
61 #endif
62