Table of Contents

fseek

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

Sets file position for stream stream and clears end-of-file indicator. For a binary stream, file position is set to offset bytes from the position indicated by origin: beginning of file for SEEK_SET, current position for SEEK_CUR, or end of file for SEEK_END. Behaviour is similar for a text stream, but offset must be zero or, for SEEK_SET only, a value returned by ftell. Returns non-zero on error.

C Sourcecode Example

#include <stdio.h> /* including standard library */
//#include <windows.h> /* uncomment this for Windows */
 
 
int main (void) {
FILE *stream;
int c;
long seek_position;
 
seek_position = 21;
 
stream=fopen("test.txt", "r" );
if (stream == 0) {
perror("cannot open file");
return 0;
}
 
fseek(stream, 0L, SEEK_SET);
while( (c=getc(stream)) != EOF) {
    putc(c, stdout);
}
 
/* SET SEEK CUR to 20 char of the file */
fseek(stream, 0L, SEEK_SET);
fseek(stream, seek_position, SEEK_CUR );
 
while( (c=getc(stream)) != EOF) {
    putc(c, stdout);
}
 
return 0;
 
}

content of test.txt

TEst 1234 iam a test file for code-reference.com just write your code down ;)

output

  output: ./fseek 
  TEst 1234 iam a test file for code-reference.com just write your code down ;)
  file for code-reference.com just write your code down ;)
  
  

see also rewind