summaryrefslogtreecommitdiff
path: root/lib/libc/stdio/fseek.c
blob: 0e425e8e9f64b2aff0928973c2207fe6770d8a4d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include "__stdio.h" // for _IO_EOF, _IO_ERR
#include "stddef.h"  // for NULL

#include <atomic.h> // for LIBC_LOCK, LIBC_UNLOCK
#include <libc.h>   // for __IMPL
#include <stdio.h>  // for FILE, fseek
#include <unistd.h> // for lseek, off_t

int fseek(FILE *stream, long offset, int whence)
{
	if (stream == NULL || __IMPL(stream)->fd < 0)
		return -1;

	LIBC_LOCK(__IMPL(stream)->lock);

	__IMPL(stream)->buf_pos = 0;
	__IMPL(stream)->buf_len = 0;
	__IMPL(stream)->flags &= ~_IO_EOF;

	off_t result = lseek(__IMPL(stream)->fd, offset, whence);

	LIBC_UNLOCK(__IMPL(stream)->lock);

	if (result == (off_t)-1) {
		__IMPL(stream)->flags |= _IO_ERR;
		return -1;
	}

	__IMPL(stream)->offset = result;
	return 0;
}