C fseek() Function

beginner
17 min

C fseek() Function

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.

Understanding the fseek() Function

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.

c
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

The whence parameter defines the position from which the offset should be added to the current position. It can take three values:

  1. SEEK_SET: The offset is relative to the beginning of the file.
  2. SEEK_CUR: The offset is relative to the current position of the file.
  3. SEEK_END: The offset is relative to the end of the file.

Practical Example 1: Reading a File from the Middle

Let's read a file starting from the middle using fseek().

c
#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.

Practical Example 2: Writing to a Specific Position

Now, let's write some data to a specific position in a file.

c
#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.

Quiz

Quick Quiz
Question 1 of 1

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! šŸŽÆ šŸš€