fseek() is a standard library function in C Language used to change the file position indicator for a given file stream.
It allows us to move the position within a file to a specified location.
int fseek(FILE *stream, long int offset, int whence);
"stream": Pointer to a FILE object that identifies the stream.
"offset": Number of bytes to offset from the origin.
"whence": Specifies the starting point for the offset calculation. It can take one of the following values:
SEEK_SET: Beginning of the file.
SEEK_CUR: Current position indicator.
SEEK_END: End of the file.
The "fseek()" function returns 0 if successful, and a non-zero value if an error occurs.
#include <stdio.h> int main() { FILE *file; // Open the file in read mode file = fopen("example.txt", "r"); // Check if file opened successfully if (file == NULL) { perror("Error opening file"); return 1; } // Move the file position indicator to the beginning of the file if (fseek(file, 0, SEEK_SET) != 0) { perror("Error seeking to beginning of file"); fclose(file); return 1; } // Close the file fclose(file); return 0; }
#include <stdio.h> int main() { FILE *file; // Open the file in read mode file = fopen("example.txt", "r"); // Check if file opened successfully if (file == NULL) { perror("Error opening file"); return 1; } // Move the file position indicator three bytes forward from the current position if (fseek(file, 3, SEEK_CUR) != 0) { perror("Error seeking relative to current position"); fclose(file); return 1; } // Close the file fclose(file); return 0; }
#include <stdio.h> int main() { FILE *file; // Open the file in read mode file = fopen("example.txt", "r"); // Check if file opened successfully if (file == NULL) { perror("Error opening file"); return 1; } // Move the file position indicator to the end of the file if (fseek(file, 0, SEEK_END) != 0) { perror("Error seeking to end of file"); fclose(file); return 1; } // Close the file fclose(file); return 0; }