I am trying to extract records from a text file named lib.txt. My program is a very simple library based management program where I will have to print all books by a given publisher or department. My code is:
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <string.h>
struct Books
{
char name[100];
char author[100];
char publisher[100];
double price;
char branch[100];
};
typedef struct Books Books;
void main()
{
int a = 0,b=0,ch,i;
char *pb = (char *)malloc(100*sizeof(char));
Books *bk;
FILE *fp;
fp = fopen("lib.txt","r");
if(fp == NULL)
{
fprintf(stderr,"\n Error to open the file \n");
exit(1);
}
while(1)
{
if(feof(fp))
{
break;
}
char c;
c = fgetc(fp);
if(c=='\n')
{
a++;
}
}
a++;
bk = (Books *)malloc(a*sizeof(Books));
while(fread(&bk[b],sizeof(Books),1,fp)) //Even tried individual character extraction but it is not working
{
b++;
if(b==a)
{
break;
}
}
for(i=0;i<a;i++)
{
printf("%s",bk[i].name);
}
printf("1. Display books supplied by a particular publisher \n");
printf("2. Display books in a particular branch \n");
printf("3. Exit");
printf("\n");
printf("Enter your choice : ");
scanf("%d",&ch);
switch(ch)
{
case 1:
{
printf("Enter the name of publisher \n");
scanf(" %s",pb);
printf("\nName\tAuthor\tPublisher\tPrice\tBranch\n");
for(i=0;i<a;i++)
{
if(strcmp(bk[i].publisher,pb)==0)
{
printf("%s\t%s\t%s\t%.2lf\t%s \n",bk[i].name,bk[i].author,bk[i].publisher,bk[i].price,bk[i].branch);
}
}
fflush(pb);
break;
}
case 2:
{
printf("Enter the name of branch \n");
scanf(" %s",pb);
printf("\nName\tAuthor\tPublisher\tPrice\tBranch\n");
for(i=0;i<a;i++)
{
if(strcmp(bk[i].publisher,pb)==0)
{
printf("%s\t%s\t%s\t%.2lf\t%s \n",bk[i].name,bk[i].author,bk[i].publisher,bk[i].price,bk[i].branch);
}
}
fflush(pb);
break;
}
case 3:
{
return;
}
default:
{
printf("Invalid choice");
}
}
free(bk);
free(pb);
fclose(fp);
getch();
}
The file lib.txt contains the following lines in same order as shown below:
Abc1 A1 P1 23.0 B1
Abc2 A2 P2 23.0 B2
Abc3 A3 P3 23.0 B3
Abc4 A4 P2 23.0 B4
Abc5 A5 P2 23.0 B5
Abc6 A6 P6 23.0 B6
Abc7 A7 P2 23.0 B7
Oh and they are seperated by tabs. Even tried with spaces but no change. The program is compiling fine but not generating desired output. Can anyone please please help? Edit: Even tried individual character extraction and then splitting into substrings but failed. Please help