Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c

What is fsetpos in C ?

Sheza Naveed

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

The fsetpos function restores the position in the stream to pos, as seen here:

int fsetpos ( FILE * stream, const fpos_t * pos );

Parameters

This function takes the following two arguments:

  1. stream - pointer to a FILE object that identifies the stream.
  2. pos - this is a pointer to fpos_t that contains a position previously retrieved by fgetpos.

Return value

The function returns zero in case of success and non-zero value in case of an error.

Example

The following code shows the use of fsetpos function followed by reading the file. The program creates a file named file.txt. We obtain the initial position of the file using fgetpos function and write “This is old text” there. fsetpos function resets the write pointer and places it at the start of the file. The new text written this overrides the old text:

#include <stdio.h>
int main () {
FILE *thisFile;
fpos_t position;
int c;
int n = 0;
thisFile = fopen("sampleFile.txt","w+");
fgetpos(thisFile, &position);
fputs("This is old text", thisFile);
fsetpos(thisFile, &position);
fputs("This is new text that will override old text", thisFile);
return(0);
}

The string “This is old text” will be replaced by “This is new text that will override old text” in the file sampleFile.txt.

RELATED TAGS

c

CONTRIBUTOR

Sheza Naveed
Copyright ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring