w3resource

C fgetpos() function

C library function - fgetpos()

The fgetpos() function is used to store the current position of the file pointer that is associated with stream into the object pointed to by pos. The value pointed to by pos can be used later in a call to fsetpos() to reposition the stream.

Syntax:

int fgetpos(FILE *stream, fpos_t *pos)

fgetpos() 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 This is the pointer to a fpos_t object. Required

Return value from fgetpos()

  • Upon successful completion, fgetpos() shall return 0; otherwise, it shall return a non-zero value and set errno to indicate the error.

Example: fgetpos() function

Following example opens the file test.txt for reading and stores the current file pointer position into the variable position.

#include <stdio.h>
#include <string.h>

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

   fp = fopen("file.txt","w+");
   fgetpos(fp, &position);
   fputs("Hello, World!", fp);
  
   fsetpos(fp, &position);
   fputs("This is going to override previous content", fp);
   fclose(fp);
   
   return(0);
}

Output:

Current position of file pointer found!

Errors: The fgetpos() function shall fail if:-

  • The file descriptor underlying stream is not valid
  • The current value of the file position cannot be represented correctly in an object of type fpos_t.
  • The file descriptor underlying stream is associated with a pipe, FIFO, or socket.

C Programming Code Editor:

Previous C Programming: C fflush()
Next C Programming: C fopen()



Share this Tutorial / Exercise on : Facebook and Twitter

C Programming: Tips of the Day

What's an object file in C?

An object file is the real output from the compilation phase. It's mostly machine code, but has info that allows a linker to see what symbols are in it as well as symbols it requires in order to work. (For reference, "symbols" are basically names of global objects, functions, etc.)

A linker takes all these object files and combines them to form one executable (assuming that it can, i.e.: that there aren't any duplicate or undefined symbols). A lot of compilers will do this for you (read: they run the linker on their own) if you don't tell them to "just compile" using command-line options. (-c is a common "just compile; don't link" option.)

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