Question- Copy a file into new file and write more data into that file and display the records;
Answer-
#include<stdio.h>
#include<conio.h>
int main()
{
struct student
{
char name[10];
char pname[5];
int term;
double fee;
}s,r,v[2];
int i;
FILE *f1,*f2;
f1=fopen(“origin.txt”,”w”);
printf(“\nNew File ORIGIN.TXT Open.”);
printf(“\nEnter name – “);
scanf(“%s”,&s.name);
printf(“\nEnter Program name – “);
scanf(“%s”,&s.pname);
printf(“\nEnter Term id -“);
scanf(“%d”,&s.term);
printf(“\nEnter Fees – “);
scanf(“%ld”,&s.fee);
fwrite(&s,sizeof(s),1,f1);
fclose(f1);
printf(“\nORIGIN.TXT Opened in read mode and NEW.TXT in write mode.”);
f1=fopen(“origin.txt”,”r”);
f2=fopen(“new.txt”,”w”);
fread(&r,sizeof(r),1,f1); //reading the data from origin.txt
fwrite(&r,sizeof(s),1,f2); //copying data to new.txt
printf(“\nCopying completed.”);
fclose(f1);
fclose(f2);
printf(“\nExsiting File NEW.TXT Open as append mode.”);
f2=fopen(“new.txt”,”a”); //in append mode the pointer in file is set to the last of file
printf(“\n\nEnter name – “);
scanf(“%s”,&s.name);
printf(“\nEnter Program name – “);
scanf(“%s”,&s.pname);
printf(“\nEnter Term id -“);
scanf(“%d”,&s.term);
printf(“\nEnter Fees – “);
scanf(“%ld”,&s.fee);
fwrite(&s,sizeof(s),1,f2);
fclose(f2);
printf(“\nExsiting File NEW.TXT Open as read mode.”);
f2=fopen(“new.txt”,”r”);
for(i=0;i<2;i++)
{
fread(&v[i],sizeof(v[i]),1,f2);
printf(“\n\nName= %s\nProgram name = %s\nTerm id = %d\nFees = %ld”,v[i].name,v[i].pname,v[i].term,v[i].fee);
}
printf(“\n\n\tPROGRAMMING @ CODE STUDIO”);
getch();
}
OUTPUT-