C++ fseek()

The fseek() function is defined in <cstdio> header file.

fseek() prototype

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

If the file is opened in binary mode, the new position of the file pointer is exactly offset bytes from the origin.

If the file is opened in text mode, the supported values for offset are:

  • Zero: It works with any value of origin i.e. SEEK_SET, SEEK_CUR and SEEK_END.
  • Value returned by a call to ftell(stream): It only works with origin of SEEK_SET.

If the stream is wide-oriented, the restrictions of both text and binary streams are applied i.e. the result of ftell is allowed with SEEK_SET and zero offset is allowed from SEEK_SET and SEEK_CUR, but not SEEK_END.

The fseek function also undoes the effects of ungetc and clears the end-of-file status, if applicable.

If a read or write error occurs, ferror is set and the file position is unaffected.


fseek() Parameters

  • stream: The file stream to modify.
  • offset: The number of characters to displace from the origin.
  • origin: Position used as reference to add to offset. It can have following values:
fseek() origin values
Value Description
SEEK_SET Beginning of file
SEEK_CUR Current position of file pointer
SEEK_END End of file

fseek() Return value

  • On success the fseek() function returns zero, nonzero otherwise.

Example: How fseek() function works?

#include <cstdio>

int main()
{
	FILE* fp = fopen("example.txt","w+");
	char ch;

	fputs("Erica 25 Berlin", fp);
	rewind(fp);

	printf("Name: ");
	while((ch=fgetc(fp))!=' ')
		putchar(ch);
	putchar('\n');
	
	printf("Age: ");
	fseek(fp,10,SEEK_SET);
	while((ch=fgetc(fp))!=' ')
		putchar(ch);
	putchar('\n');

	printf("City: ");
	fseek(fp,15,SEEK_SET);
	while((ch=fgetc(fp))!=EOF)
		putchar(ch);
	putchar('\n');

	fclose(fp);
	return 0;
}

When you run the program, the output will be:

Name: Erica
Age: 25
City: Berlin

Also Read:

Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges