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