fseek() in C programming

File Handling : fseek() in C programming

File Handling in C programming is a prime feature which helps to operate larger files without any obstruction and also helps us to perform various functions such as read,write,etc. any file which is stored on our local system using C Language. File handling helps to eliminate the problem of handling and displaying large amount of data.In this section, we will learn the fseek() function of file handling in C programming.
fseek() in C programming

fseek() function in C programming:

fseek() function of file handling in C language is used to change the file pointer from a specific file position to the requested location. This function helps in faster modification of file contents.After the file pointer has shifted to a specified offset, you can perform any operation like writing, reading from the file according to your requirement or wish. This helps to write data into file at requested location.

Syntax of fseek() :

int fseek(FILE *pointer, long int offset, int position);

There are various parts of this syntax which are mentioned below:

  • Pointer- It is used to point to the File object that helps to find the stream in which data is to be written.
  • Offset- It represents the number of bytes to the offset from the specified position.
  • Position- It specifies the position according to which the file pointer needs to be moved and from where the offset is to be added.There are 3 values which are
  1. SEEK_END – It represents the end of file.
  2. SEEK_SET – It represents the start of file.
  3. SEEK_CUR – It represents the current position of the file pointer.

Example 1:

Run

#include<stdio.h>
int main (void) 
{
   FILE *new;
   new = fopen("sample.txt","w");
   fseek( new , 7, SEEK_SET ); 
   fclose(new);
   return 0;
}

The above code sets the pointer of the file 7 places ahead from the start of the file using the SEEK_SET argument.

Example 2:

Run
#include
int main (void) 
{
   FILE *new;
   new = fopen("sample.txt","w");
   fseek( new , 0, SEEK_END ); 
   fclose(new);
   return 0;
}
The above code sets the pointer of the file to the end location of the file using the SEEK_END argument.

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription