Welcome back to CodeYourCraft! Today, we're diving into a fascinating aspect of C programming - File Positioning. This lesson is perfect for beginners and intermediates alike. Let's get started!
In C programming, we often need to read and write data from files. But what if we want to access specific parts of a file? That's where file positioning comes in handy! 🎯
Before we dive into file positioning, let's understand what a file pointer is. In C, a file pointer is a variable that stores the current position of the file.
FILE *filePtr; // Declare a file pointerNow that we understand file pointers, let's see how to move around in a file.
fseek() Function 💡The fseek() function is used to change the position of the file pointer.
int fseek(FILE *stream, long int offset, int whence);stream: The file stream to be moved.offset: The number of bytes to move the file pointer.whence: Determines from where the offset is to be added. It can have three values:
SEEK_SET: Offset is relative to the beginning of the file.SEEK_CUR: Offset is relative to the current position of the file pointer.SEEK_END: Offset is relative to the end of the file.Example:
#include <stdio.h>
int main() {
FILE *filePtr;
filePtr = fopen("example.txt", "r"); // Open the file in read mode
if (filePtr == NULL) {
printf("Unable to open file.\n");
return 1;
}
fseek(filePtr, 2, SEEK_SET); // Move the file pointer to the 3rd position (index starts from 0)
char c;
fread(&c, sizeof(char), 1, filePtr); // Read the character at the current position
printf("The character at the 3rd position is: %c\n", c);
fclose(filePtr); // Close the file
return 0;
}In this example, we're reading the third character of a file named example.txt using the fseek() function.
ftell() Function 💡The ftell() function returns the current position of the file pointer.
long int ftell(FILE *stream);Example:
#include <stdio.h>
int main() {
FILE *filePtr;
filePtr = fopen("example.txt", "r"); // Open the file in read mode
if (filePtr == NULL) {
printf("Unable to open file.\n");
return 1;
}
long int currentPos = ftell(filePtr); // Get the current position of the file pointer
printf("The current position of the file pointer is: %ld\n", currentPos);
fclose(filePtr); // Close the file
return 0;
}In this example, we're finding the current position of the file pointer.
What does the `fseek()` function do in C programming?
And that's a wrap for today! We've learned about file positioning in C programming. We've discussed file pointers, the fseek() function, and the ftell() function.
In the next lesson, we'll dive deeper into file handling in C programming. Until then, keep coding and learning! 💡