File Handling Assignment-1
File Handling Assignment-1
Write a program to read the integer value from keyboard and store the same content
in a file "data.txt" using write mode.
#include<stdio.h>
int main()
int n,p;
FILE *fp;
fp=fopen("data.txt","w+");
scanf("%d",&n);
putw(n,fp);
rewind(fp);
p=getw(fp);
fclose(fp);
return 0;
2. write a program to read the character from keyboard and store the same content in a
file using write and read mode.
#include<stdio.h>
int main()
{
char n,p;
FILE *fp;
fp=fopen("data2.txt","w+");
scanf("%c",&n);
putc(n,fp);
rewind(fp);
p=getc(fp);
fclose(fp);
return 0;
3. Write a program to read the string from keyboard and store the same content in a file
using append mode.
#include<stdio.h>
int main()
char str[50],st[50];
FILE *fp;
fp=fopen("data3.txt","w+");
fgets(str,50,stdin);
fputs(str,fp);
rewind(fp);
fgets(st,50,fp);
fclose(fp);
return 0;
4. write a program to create a structure of book with book title, author name and price
and store all book records for n books in a file.
#include<stdio.h>
int main()
FILE *fp;
struct books
char book_title[50];
char author_name[50];
int book_price;
};
int n,i;
char str[1000];
fp=fopen("data4.txt","w+");
scanf("%d",&n);
for(i=0;i<n;i++)
scanf("%s",&book[i].book_title);
scanf("%s",&book[i].author_name);
scanf("%d",&book[i].book_price);
fprintf(fp,"\n\tPrice: %d\n",book[i].book_price);
}
rewind(fp);
while(!feof(fp))
fgets(str,1000,fp);
printf("%s",str);
return 0;
5 Write a program create a structure of bank with accno, holder name and balance and
store them in a file for n holders.
#include<stdio.h>
int main()
FILE *fp;
struct bank
int accno;
char holder_name[50];
int balance;
};
int n,i;
char str[1000];
fp=fopen("data5.txt","w+");
scanf("%d",&n);
for(i=0;i<n;i++)
scanf("%d",&account[i].accno);
scanf("%s",&account[i].holder_name);
scanf("%d",&account[i].balance);
fprintf(fp,"\n\tBalance:
%d\n",account[i].balance);
rewind(fp);
while(!feof(fp))
{
fgets(str,1000,fp);
printf("%s",str);
return 0;
6. Write a program to take three numbers from users using structure and write it into
binary file using fwrite().
#include<stdio.h>
int main()
FILE *fp;
struct numbers{
int num1;
int num2;
int num3;
}number,sec_no;
fp=fopen("number.bin","wb+");
scanf("%d %d
%d",&number.num1,&number.num2,&number.num3);
fwrite(&number,sizeof(number),1,fp);
rewind(fp);
fread(&sec_no,sizeof(sec_no),1,fp);
fclose(fp);
#include<stdio.h>
int main()
struct college{
int stu_id;
char stud_name[30];
}students[100],clg_studs[100];
FILE *fp;
int n,i;
fp=fopen("studentdetails.bin","wb+");
scanf("%d",&n);
for(i=0;i<n;i++)
scanf("%d",&students[i].stu_id);
scanf("%s",&students[i].stud_name);
fwrite(&students,sizeof(students),n,fp);
rewind(fp);
fread(&clg_studs,sizeof(clg_studs),n,fp);
for(i=0;i<n;i++)
printf("\nName of student:
%s",clg_studs[i].stud_name);
fclose(fp);
return 0;