PatchworkOS
Loading...
Searching...
No Matches
ftell.c
Go to the documentation of this file.
1#include <errno.h>
2#include <limits.h>
3#include <stdio.h>
4
5#include "user/common/file.h"
6
7long int ftell(FILE* stream)
8{
9 /* ftell() must take into account:
10 - the actual *physical* offset of the file, i.e. the offset as recognized
11 by the operating system (and stored in stream->pos.offset); and
12 - any buffers held by PDCLib, which
13 - in case of unwritten buffers, count in *addition* to the offset; or
14 - in case of unprocessed pre-read buffers, count in *substraction* to
15 the offset. (Remember to count ungetidx into this number.)
16 Conveniently, the calculation ( ( bufend - bufidx ) + ungetidx ) results
17 in just the right number in both cases:
18 - in case of unwritten buffers, ( ( 0 - unwritten ) + 0 )
19 i.e. unwritten bytes as negative number
20 - in case of unprocessed pre-read, ( ( preread - processed ) + unget )
21 i.e. unprocessed bytes as positive number.
22 That is how the somewhat obscure return-value calculation works.
23 */
24 /* If offset is too large for return type, report error instead of wrong
25 offset value.
26 */
27 long int result;
28 mtx_lock(&stream->mtx);
29
30 if ((stream->pos.offset - stream->bufEnd) > (LONG_MAX - (stream->bufIndex - stream->ungetIndex)))
31 {
32 /* integer overflow */
33 mtx_unlock(&stream->mtx);
34 errno = ERANGE;
35 return -1;
36 }
37
38 result = (stream->pos.offset - (((int)stream->bufEnd - (int)stream->bufIndex) + stream->ungetIndex));
39 mtx_unlock(&stream->mtx);
40 return result;
41}
long int ftell(FILE *stream)
Definition ftell.c:7
#define ERANGE
Math result not representable.
Definition errno.h:202
#define errno
Error number variable.
Definition errno.h:27
#define LONG_MAX
Definition limits.h:28
Definition file.h:34
fpos_t pos
Definition file.h:41
uint64_t bufIndex
Definition file.h:39
uint64_t bufEnd
Definition file.h:40
mtx_t mtx
Definition file.h:45
uint64_t ungetIndex
Definition file.h:43
uint64_t offset
Definition file.h:28
_PUBLIC int mtx_lock(mtx_t *mtx)
Definition mtx_lock.c:11
_PUBLIC int mtx_unlock(mtx_t *mtx)
Definition mtx_unlock.c:10