Share on Google+Share on Google+

C file fseek() function

This section demonstrates the use of fseek() function in C.

C file fseek() function

This section demonstrates the use of fseek() function in C. This function sets the file position indicator for the stream pointed to by stream or you can say it seeks a specified place within a file and modify it.

Its syntax is:  fseek(FILE *stream, long int offset, int whence)

The value of whence must be one of the constants SEEK_SET, SEEK_CUR, or SEEK_END, to indicate whether the offset is relative to the beginning of the file, the current file position, or the end of the file, respectively.Now,we will explain you with an example.
In the following code, the function fopen(file, "w") open a file and allow to perform write operations into the file. The fputs() function writes the string "Hello World"  into the file. Then we have used fseek( f , 6 , SEEK_SET ) function which sets the file position indicator to 6 and the fputs() function write the string "India"  in place of "World".


Hello World

Here is the code:

#include <stdio.h>

int main() {
       FILE * f;
       f = fopen("myfile.txt", "w");
       fputs("Hello World", f);
       fseek(f, 6, SEEK_SET);
       fputs(" India", f);
       return 0;

Now the file consist of following data:

Hello India



Posted on: December 17, 2009 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.


Advertisement null