I haven't been studying c programming for that long but over the christmas break i was asked to code a simple database program.
Problem 1: Looking at the file after compiling and adding a record, only occasionally something would show upCode:/*-------------Library Headers--------------*/ #include <stdio.h> #include <stdlib.h> /*-----------function prototypes-------------*/ void menu(void); void add(void); void search(void); void delete(void); struct { int student_no; char firstname[15]; char surname[15]; int mark; } student; /*--------------Main------------------------*/ int main() { FILE *pFile; pFile = fopen("database.txt","w"); system("CLS"); menu(); getch(); return 0; } /*---------------Function menu-----------------*/ void menu() { int choice; printf("[1] Enter a student\n"); printf("[2] Search a student by first name\n"); printf("[3] Delete a student\n"); printf("[4] Exit program\n"); scanf("%d", &choice); switch(choice){ case 1: add(); break; case 2: search(); break; case 3: delete(); break; case 4: exit(0); break; default: printf("Incorrect entry "); menu(); break; } } /*---------------Function Add-----------------*/ void add() { FILE *pFile; char answer; int student_no; system("cls"); printf("First Name: "); scanf("%s", student.firstname); printf("Surname: "); scanf("%s", student.surname); printf("\nAge: "); scanf("%d", &student.mark); pFile = fopen("database.txt","w"); fprintf(pFile, "\n%s\t%s\t%d\t", student.firstname, student.surname, student.mark); fclose(pFile); printf("A student has been added successfully\n"); printf("Are there any more people? \n[1] for yes \n[0] for no\n"); scanf("%d", &answer); if (answer == 1) { add(); } if (answer == 0) { menu(); } } /*---------------Function Search -----------------*/ void search() { int found, length; char studentname [15]; FILE *pFile; printf("Enter student first name: "); scanf("%s", &studentname); printf("Searching for %s\n",studentname); found = 0; if ((pFile=fopen("database.txt","r"))==NULL) { printf("File is empty/missing"); } else { while(!feof(pFile) && found == 0) { fscanf(pFile,"\n%s\t%s\t%d",student.firstname, student.surname, student.mark); length = strlen (student.firstname); found == 1; } } if (found) { printf("Record found.\n"); printf("First Name: %s\nSurname: %s\nMark: %d \n",student.firstname, student.surname, student.mark); } else { printf("not found"); getch(); } } /*---------------Function Delete-----------------*/ void delete() { }
Problem 2: when i search for the record that is there the program stops responding and exits...
all help is appreciated