w3resource

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.

Syntax:

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);
  fclose(fp);

  //FILE *fp;
  int c;

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

Output:

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.