The C library fgetpos(FILE *stream, fpos_t *pos) function gets the current file position of the stream and writes it to pos. It stores the position in a variable of type fpos_t. This function is useful when you need to save a specific location in a file and return to it later.
SyntaxFollowing is the C library syntax of the fgetpos() function −
int fgetpos(FILE *stream, fpos_t *pos);Parameter
This function accepts two parameter −
The fgetpos() function returns 0 on success and it returns a non-zero value on failure.
Example 1: Simple Position FetchThis example shows how to get and print the current position in a file.
Below is the illustration of C library fgetpos() function.
#include <stdio.h> int main() { FILE *file = fopen("example1.txt", "w+"); if (file == NULL) { perror("Failed to open file"); return 1; } fputs("Hello, World!", file); fpos_t pos; // Get the current file position if (fgetpos(file, &pos) != 0) { perror("fgetpos failed"); fclose(file); return 1; } printf("Current position: %ld\n", (long)pos); fclose(file); return 0; }Output
The above code wites "Hello, World!" to the file and fetches the position, which is 13 because "Hello, World!" has 13 characters including the space and punctuation.−
Current position: 13Example 2: Reading and Rewinding in a File
In this example it shows reading from a file, saving the position, and then rewinding to the saved position.
#include <stdio.h> int main() { FILE *file = fopen("example3.txt", "w+"); if (file == NULL) { perror("Failed to open file"); return 1; } fputs("Line 1\nLine 2\nLine 3\n", file); fpos_t pos; // Rewind to the start of the file rewind(file); char buffer[20]; fgets(buffer, sizeof(buffer), file); printf("First read: %s", buffer); // Save the current position after reading the first line if (fgetpos(file, &pos) != 0) { perror("fgetpos failed"); fclose(file); return 1; } fgets(buffer, sizeof(buffer), file); printf("Second read: %s", buffer); // Return to the saved position if (fsetpos(file, &pos) != 0) { perror("fsetpos failed"); fclose(file); return 1; } fgets(buffer, sizeof(buffer), file); printf("Re-read after fsetpos: %s", buffer); fclose(file); return 0; }Output
After execution of above code, it writes multiple lines to a file, reads the first line, saves the position, reads the second line, then returns to the saved position and reads the second line again.
First read: Line 1 Second read: Line 2 Re-read after fsetpos: Line 2
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4