C fsetpos() function

C library function - fsetpos()

The fsetpos() function shall set the file position and state indicators for the stream pointed to by stream according to the value of the object pointed to by pos, which the application shall ensure is a value obtained from an earlier call to fgetpos() on the same stream. If a read or write error occurs, the error indicator for the stream shall be set and fsetpos() fails.


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

fsetpos() Parameters:

Name Description Required /Optional
stream Identifies an address for a file descriptor, which is an area of memory associated with an input or output stream. Required
pos Pointer of fpos_t object contains a position previously obtained with fgetpos. Required

Return value from fsetpos()

  • The fsetpos() function shall return 0 if it succeeds; otherwise, it shall return a non-zero value and set errno to indicate the error.

Example: fsetpos() function

In the following code fsetpos() reset the write pointer at the beginning of the file so the text "Next - cpp programming." has written in the text instead of "C programming."

#include <stdio.h>

int main() {
  FILE * fp;
  fpos_t position;

  fp = fopen("test.txt", "w+");
  fgetpos(fp, & position);
  fputs("C programming.", fp);

  fsetpos(fp, & position);
  fputs("Next - cpp programming.", fp);

  //FILE *fp;
  int c;

  fp = fopen("test.txt", "r");
  while (1) {
    c = fgetc(fp);
    if (feof(fp)) {
    printf("%c", c);
  return (0);


Next - cpp programming.

C Programming Code Editor:

Contribute your code and comments through Disqus.

Previous C Programming: C freopen()
Next C Programming: C ftell()

Follow us on Facebook and Twitter for latest update.

C Programming: Tips of the Day

Reading a string with scanf :

An array "decays" into a pointer to its first element, so scanf("%s", string) is equivalent to scanf("%s", &string[0]). On the other hand, scanf("%s", &string) passes a pointer-to-char[256], but it points to the same place.

Then scanf, when processing the tail of its argument list, will try to pull out a char *. That's the Right Thing when you've passed in string or &string[0], but when you've passed in &string you're depending on something that the language standard doesn't guarantee, namely that the pointers &string and &string[0] -- pointers to objects of different types and sizes that start at the same place -- are represented the same way.

Ref : https://bit.ly/3pdEk6f