my program should accept some structures variables form the user in a structure array, write those variables to a txt file then read the data from the txt file and print them but the program keeps crashing after writing to the text file. I think the problem is with my booksearch() function but i cant seem to diagnose the problem. The function was working some time back but was just reading a lot of garbage from the file (and i verified the file had all the correct data that was inputted) so i made some changes and now cant get it to work.
im using sequential access file so please point me to my errors and any suggestions would be appreciated.
my code so far:
Code:
#include<stdio.h>
#include<conio.h>
void booksearch();
void enterstuddata();
void writetofile();
//-------------------------------------
struct studentfile{
char s_name[30];
int s_id;
char s_faculty[40];
int s_contactnum;
float s_loanbal;
int s_brrwamnt;
};
void main()
{
struct studentfile s[10];
enterstuddata(s);
booksearch();
}
//-------------------------------------
void enterstuddata(struct studentfile stud[])
{
int count, size, *s_ptr;
size = 2;
for(count=0;count<size;count++)
{
printf("Enter student name: ");
fflush(stdin);
gets(stud[count].s_name);
printf("Enter student ID: ");
scanf("%d", &stud[count].s_id);
fflush(stdin);
printf("Enter student faculty: ");
gets(stud[count].s_faculty);
printf("Enter student contact number: ");
scanf("%d", &stud[count].s_contactnum);
printf("Enter student loan balance: ");
scanf("%f", &stud[count].s_loanbal);
stud[count].s_brrwamnt = 0;
printf("\n");
}
s_ptr = &count;
writetofile(stud, *s_ptr);
}
//-------------------------------------
void writetofile(struct studentfile stud[],int size)
{
int count;
FILE *studfile;
studfile = fopen("students.txt", "w");
if(studfile != NULL){
for(count=0;count<size;count++){
fprintf(studfile, "%s %d %s %d %f %d\n", stud[count].s_name, stud[count].s_id, stud[count].s_faculty,
stud[count].s_contactnum, stud[count].s_loanbal, stud[count].s_brrwamnt);
}
fclose(studfile);
}else{
printf("ERROR!!: StudentData file could not be opened for writing");
}
}
//----------------------------------------
void booksearch(){
FILE *bkptr;
char name[30], fac[40];
int id, num;
float bal;
bkptr = fopen("students.txt", "r");
if(bkptr != NULL){
fscanf(bkptr, "%s %d %s %d %f", name, &id, fac, &num, bal);
fclose(bkptr);
printf("%s\n %d\n %s\n %d\n %f\n", name, id, fac, num, bal);
}else{
printf("ERROR!!: BookData file could not be opened for writing");
}
}