The C library fsetpos() function sets the file position of the given stream to the given position. The argument pos is a position given by the function fgetpos.This function is part of the <stdio.h> library and is particularly useful for random access to files.
SyntaxFollowing is the C library syntax of fsetpos() function −
int fsetpos(FILE *stream, const fpos_t *pos);Parameter
This function accepts following parameters
The fsetpos() function returns 0 on success and returns a non-zero value on error.
Example 1This example demonstrates setting the file position to the beginning of the file after writing to it.
#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; fgetpos(file, &pos); // Get the current position rewind(file); // Set position to the beginning fsetpos(file, &pos); // Set back to the saved position fputs(" Overwrite", file); fclose(file); return 0; }Output
The above code produces following result−
Hello, World! OverwriteExample 2
Using fsetpos()to Move to a Specific Position
This example demonstrates moving to a specific position in the file and modifying content.
#include <stdio.h> int main() { FILE *file = fopen("example2.txt", "w+"); if (file == NULL) { perror("Failed to open file"); return 1; } fputs("1234567890", file); fpos_t pos; fgetpos(file, &pos); // Get the current position pos.__pos = 5; // Set position to 5 fsetpos(file, &pos); // Move to position 5 fputs("ABCDE", file); fclose(file); return 0; }Output
After execution of above code, we get the following result
12345ABCDEExample 3
Saving and Restoring File Positions
This example demonstrates saving a file position, performing some operations, and then restoring the original position.
#include <stdio.h> int main() { FILE *file = fopen("example3.txt", "w+"); if (file == NULL) { perror("Failed to open file"); return 1; } fputs("Original content", file); fpos_t pos; fgetpos(file, &pos); // Save the current position fseek(file, 0, SEEK_END); // Move to the end of the file fputs("\nNew content", file); fsetpos(file, &pos); // Restore the original position fputs(" modified", file); fclose(file); return 0; }Output
The output of the above code is as follows −
Original modified content New content
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