The rewind function is used to move the position of file pointer to the beginning of file. The rewind() function is useful if we want to update a given file.
struct instrument
{
int id;
char name[30];
float price;
}instr;
int main()
{
int n,i;
FILE *fp;
fp=fopen("inst1.dat","wb+");
if(fp==NULL)
{
printf("Error in opening file\n");
return 0;
}
//Accepting number of records for writing
printf("How many records do you want?\n");
scanf("%d",&n);
printf("\n--------Writing in file using fwrite-----------\n\n");
//Writing records one by one in file
for(i=0;i
{
printf("Enter the details of instrument:\n");
printf("Enter Instrument Id :\n");
scanf("%d",&instr.id);
printf("Enter Instrument Name :\n");
scanf("%s",instr.name);
printf("Enter Instrument Price :\n");
scanf("%f",&instr.price);
printf("\n");
//for writing the entire record to the file
fwrite(&instr,sizeof(instr),1,fp);
}
printf("\n\n--------Usage of rewind()-----------\n\n");
//Moving file pointer to the begining of file
fseek(fp,0,0);
printf("Position pointer in the begining-> %ld\n",ftell(fp));
//Moving file pointer to the end of file
fseek(fp,0,2);
printf("Position pointer at the end of file-> %d\n",ftell(fp));
//Moving file pointer to the begining of file using rewind
rewind(fp);
printf("Position pointer after rewind -> %d\n",ftell(fp));
fclose(fp);
}
0 comments: