]> pd.if.org Git - pdclib/blob - functions/stdio/_PDCLIB_ftell64.c
PDCLIB-7: Add _PDCLIB_ftell64 to give us full precision file positioning information...
[pdclib] / 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 \r
15 uint_fast64_t _PDCLIB_ftell64( struct _PDCLIB_file_t * stream )\r
16 {\r
17     /* ftell() must take into account:\r
18        - the actual *physical* offset of the file, i.e. the offset as recognized\r
19          by the operating system (and stored in stream->pos.offset); and\r
20        - any buffers held by PDCLib, which\r
21          - in case of unwritten buffers, count in *addition* to the offset; or\r
22          - in case of unprocessed pre-read buffers, count in *substraction* to\r
23            the offset. (Remember to count ungetidx into this number.)\r
24        Conveniently, the calculation ( ( bufend - bufidx ) + ungetidx ) results\r
25        in just the right number in both cases:\r
26          - in case of unwritten buffers, ( ( 0 - unwritten ) + 0 )\r
27            i.e. unwritten bytes as negative number\r
28          - in case of unprocessed pre-read, ( ( preread - processed ) + unget )\r
29            i.e. unprocessed bytes as positive number.\r
30        That is how the somewhat obscure return-value calculation works.\r
31     */\r
32 \r
33     /* ungetc on a stream at offset==0 will cause an overflow to UINT64_MAX.\r
34      * C99/C11 says that the return value of ftell in this case is \r
35      * "indeterminate"\r
36      */\r
37 \r
38     return ( stream->pos.offset - ( ( (int)stream->bufend - (int)stream->bufidx ) + (int)stream->ungetidx ) );\r
39 }\r
40 \r
41 #endif\r
42 \r
43 #ifdef TEST\r
44 #include <_PDCLIB_test.h>\r
45 \r
46 #include <stdlib.h>\r
47 \r
48 int main( void )\r
49 {\r
50     /* Tested by ftell */\r
51     return TEST_RESULTS;\r
52 }\r
53 \r
54 #endif\r
55 \r