Welcome to our comprehensive guide on the fseek() function in C programming! Let's dive into this powerful tool that allows us to manipulate the file position in C.
The fseek() function is used to change the file position indicator for the stream pointed by FILE *stream to an absolute position specified by the offset and whence.
int fseek(FILE *stream, long int offset, int whence);š” Pro Tip: The fseek() function returns zero if the file position was successfully changed, or a non-zero value if an error occurred.
The whence parameter defines the position from which the offset should be added to the current position. It can take three values:
SEEK_SET: The offset is relative to the beginning of the file.SEEK_CUR: The offset is relative to the current position of the file.SEEK_END: The offset is relative to the end of the file.Let's read a file starting from the middle using fseek().
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE *file = fopen("example.txt", "r");
if (file == NULL) {
printf("Unable to open file.\n");
return 1;
}
// Move the file position indicator to the middle of the file.
fseek(file, sizeof(char) * (ftell(file) / 2), SEEK_SET);
char c;
while ((c = fgetc(file)) != EOF) {
printf("%c", c);
}
fclose(file);
return 0;
}š Note: This example assumes that example.txt is a text file with odd number of lines.
Now, let's write some data to a specific position in a file.
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE *file = fopen("example.txt", "w+");
if (file == NULL) {
printf("Unable to open file.\n");
return 1;
}
// Write some data to the beginning of the file.
fprintf(file, "Hello, World!\n");
// Move the file position indicator to the end of the file.
fseek(file, 0, SEEK_END);
// Write some more data to the end of the file.
fprintf(file, "From the middle!\n");
fclose(file);
return 0;
}In this example, we've written "Hello, World!" at the beginning of the file, then moved to the end using fseek(), and wrote "From the middle!" to the end of the file.
What does the `fseek()` function do in C programming?
With that, you now have a solid understanding of the fseek() function in C programming! Happy coding! šÆ š