Q1. Write a C program to create a data file "booklist.txt" which stores book_id, book_name and book_author according to user want and display all records of file "booklist.txt"
#include<stdio.h>
int main()
{
int book_id;
char book_name[30],book_author[30];
char ch='y';
FILE *fp;
fp=fopen("booklist.txt","w");
while(ch!='n')
{
printf("Enter book id, name and author: ");
scanf("%d%s%s",&book_id,book_name,book_author);
fprintf(fp,"%d\t %s\t %s\n",book_id,book_name,book_author);
printf("Add more records : ");
scanf(" %c",&ch);
}
fclose(fp);
fp=fopen("booklist.txt","r");
while(fscanf(fp,"%d%s%s",&book_id,book_name,book_author)!=EOF)
{
printf("%d\t %s\t %s\n ",book_id,book_name,book_author);
}
fclose(fp);
}
Q2. Write C Program to create a data file named "student.txt" and store data under fields name, class and mark in computer. Progam should terminate according to user's choice. After that display them.
#include<stdio.h>
int main()
{
int student_class,computer_mark;
char student_name[30];
char ch='y';
FILE *fp;
fp=fopen("student.txt","w");
while(ch!='n')
{
printf("Enter student name, class and mark in computer: ");
scanf("%s%d%d",student_name,&student_class,&computer_mark);
fprintf(fp,"%s\t %d\t %d\n",student_name,student_class,computer_mark);
printf("Add more records : ");
scanf(" %c",&ch);
}
fclose(fp);
fp=fopen("student.txt","r");
while(fscanf(fp,"%s%d%d",student_name,&student_class,&computer_mark)!=EOF)
{
printf("%s\t %d\t %d\n ",student_name,student_class,computer_mark);
}
fclose(fp);
}
Q3. Let, a datafile named 'book.txt' contains information of books (name,price,edition). Write a program in C language to add some more data and then print all the records of books having price more than 900.
#include<stdio.h>
int main()
{
{
char book_name[30],book_edition[10];
float book_price;
char ch='y';
FILE *fp;
fp=fopen("book.txt","a");
while(ch!='n')
{
printf("Enter Book name, price and edition : ");
scanf("%s%f%s",book_name,&book_price,book_edition);
fprintf(fp,"%s\t %f\t %s\n",book_name,book_price,book_edition);
printf("Add more records : ");
scanf(" %c",&ch);
}
fclose(fp);
fp=fopen("book.txt","r");
while(fscanf(fp,"%s%f%s",book_name,&book_price,book_edition)!=EOF)
{
if(book_price>900)
printf("%s\t %f\t %s\n ",book_name,book_price,book_edition);
}
fclose(fp);
}
Q4. Write a C program to create a data file "booklist.txt" which stores five records under heading book_id, book_name and book_author .
#include<stdio.h>
int main()
{
int book_id,i;
char book_name[30],book_author[30];
FILE *fp;
fp=fopen("booklist.txt","w");
for(i=0;i<5;i++)
{
printf("Enter book id, name and author: ");
scanf("%d%s%s",&book_id,book_name,book_author);
fprintf(fp,"%d\t %s\t %s\n",book_id,book_name,book_author);
}
fclose(fp);
}