File Positioning Functions
File Positioning Functions
• int main() {
• FILE *file;
•
• // Open a file in write mode
• file = fopen("example.txt", "w");
•
• // Write content to the file
• fprintf(file, "This is line 1.\n");
• fprintf(file, "This is line 2.\n");
• fprintf(file, "This is line 3.\n");
• // Use fseek to move the file pointer to the beginning of the second line
• fseek(file, 18, SEEK_SET);
• // Use rewind to move the file pointer to the beginning of the file
• rewind(file);
• // Read and print the content from the beginning of the file
• fgets(buffer, sizeof(buffer), file);
• printf("Content from the beginning: %s", buffer);
• return 0;
• Explanation:
• We open a file in write mode ("w") and write three lines of text to it
using fprintf.
• After closing the file, we open it again in read mode ("r").
• We use fseek to move the file pointer to the beginning of the
second line (character 18).
• We read and print the content from the second line using fgets.
• We use ftell to get the current position of the file pointer and print
it.
• We use rewind to move the file pointer back to the beginning of the
file.
• We read and print the content from the beginning of the file using
fgets.
• This example demonstrates how to use file positioning functions to
navigate within a file and read specific portions of its content.