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