Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C

fseek — C23 stream function

`fseek(stream, offset, whence)` from `<stdio.h>` sets a stream file position relative to `SEEK_SET`, `SEEK_CUR`, or `SEEK_END`. It returns `0` on success and a nonzero value on failure; success clears the end-of-file indicator and undoes effects of `ungetc`.

Version: C23

Syntax

int fseek(FILE *stream, long int offset, int whence);

fseek(stream, offset, whence) from <stdio.h> sets a stream file position relative to SEEK_SET, SEEK_CUR, or SEEK_END. It returns 0 on success and a nonzero value on failure; success clears the end-of-file indicator and undoes effects of ungetc.

The example writes ABCDE, seeks two bytes from SEEK_SET, and reads C. It then reads to the end, observes feof == 1, seeks back to the start, and prints C 1 0, demonstrating that successful positioning clears EOF.

On a binary stream the offset is measured in bytes, although support for SEEK_END is not required. For a text stream, only offset 0 or a value previously returned by ftell used with SEEK_SET is portable. After failure the position may be indeterminate; do not seek a stream that does not support positioning.

Examples

#include <stdio.h>
int main(void){FILE *stream=tmpfile();if(!stream)return 1;if(fputs("ABCDE",stream)==EOF||fseek(stream,2L,SEEK_SET)!=0){fclose(stream);return 1;}int selected=fgetc(stream);while(fgetc(stream)!=EOF){}int before=feof(stream)!=0;if(fseek(stream,0L,SEEK_SET)!=0){fclose(stream);return 1;}int after=feof(stream)!=0;printf("%c %d %d\n",selected,before,after);return fclose(stream)==0?0:1;}

Result

C 1 0

The example writes `ABCDE`, seeks two bytes from `SEEK_SET`, and reads `C`. It then reads to the end, observes `feof == 1`, seeks back to the start, and prints `C 1 0`, demonstrating that successful positioning clears EOF.

Sources