Calling the function directly works but calling from another function fails - c

When I use the display_menu function to call read_txt_file() it doesn't work. I am unable to get the file contents to the stdout but when I use the read_txt_file() directly, it works. I can see the contents of the file in stdout. What is the problem with the display_menu?
#include <stdio.h>
typedef struct filename
{
int age;
char name[100];
}name_t;
name_t * fname=NULL;
void quit()
{
printf("\nPress enter to exit");
fflush(stdin);
getchar();
}
enter(char prompt[])
{
puts(prompt);
fflush(stdin);
getchar();
}
void read_txt_file()
{
char ch;
fname=(name_t *)malloc(sizeof(name_t));
FILE *fptr=NULL;
atexit(quit);
printf("Please enter the file name to read : ");
fflush(stdin);
scanf("%s",fname->name);
fptr=fopen(fname->name,"r");
if(fptr == NULL)
{
perror("Could not open the file ");
return;
}
printf("+++++++++++++++++++++++++++++++++++++++++++++++++");
printf("Contents of the file %s are : ",fname->name);
**while(ch != EOF)
{
ch=fgetc(fptr);
printf("%c",ch);
}**
enter("press enter");
fclose(fptr);
}
display_menu()
{
int choice;
while(1)
{
system("cls");
printf("\t\t1.read and display from a file\n \
\b2.quit\n");
scanf("%d",&choice);
switch(choice)
{
case 1 :
read_txt_file();
break;
case 2 :
exit(0);
default :
printf("please enter proper choice(1-3)\n Enter to continue");
fflush(stdin);
getchar();
}
}
}
int main()
{
/*
read_txt_file();
*/
**display_menu();**
return 0;
}

After the scanf("%d",&choice); call, the input will still have a '\n' (the one of the return you pressed to enter the choice). So the file name will be empty. You can add a getchar() after reading the choice (to remove the '\n').

Related

Bugs in C Switch Menu using a Char as Choice, Won't Read in fgets name

Im basically Writing a program that creates, reads, updates and
deletes records in a binary file.
Everything compiles correctly, no syntax errors, but I do have some
bugs.
KNOWN BUGS
1.) Imputing any strings does not work, using fgets
2.) Ctrl-D Does Work but outputs a 'default' error before it exits.
3.) Update does not work (Not my main issue at the moment as the others are more important for now.)
4?) I'm not sure if the menu is working how it's supposed to work. I
think the do while is correct, since in the menu if I select and hit
CTRL-D it does exit the program. Just wanna be sure.
Right now I just want to know why, It is skipping the courseName in
the inputs function.
Here is my code thus far
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <errno.h>
#include <string.h>
typedef struct{
char courseName [64];
char courseSched [4];
unsigned int courseHours;
unsigned int courseSize;} COURSE;
FILE *pfileCourse;
int courseNumber = 0;
//Prototypes
void inputDetails(COURSE *c);
void readCourseRecord();
void createCourseRecord();
void print_menu();
void modifyCourseInfo();
void deleteCourse();
void display(COURSE c);
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main(int argc, char *argv[]) {
char choice; // this is the choice
printf("Enter one of the following actions or press CTRL-D to exit\n");
printf("C - Create a new course record\n");
printf("R - Read an existing course record\n");
printf("U - Update an existing course record\n");
printf("D - Delete an existing course record\n");
do{
choice = getchar();
switch(choice) {
case 'c':
case 'C':
printf("YOU PICKED C for Create\n");
createCourseRecord();
break;
case 'r':
case 'R':
printf("This is Choice R\n");
readCourseRecord();
break;
case 'u':
case 'U':
printf("Here is where you update an existing course\n");
modifyCourseInfo();
break;
case 'd':
case 'D':
printf("here is where you Delete an existing course record\n");
deleteCourse();
break;
default:
printf("Wrong Choice!\n");
}
}while(choice != EOF);
return 0;
}
void createCourseRecord() {
COURSE data;
pfileCourse = fopen("courses.dat", "ab");
printf("Please Enter The Details of The Course\n");
inputDetails(&data);
fwrite(&data, sizeof(data), 1, pfileCourse);
fclose(pfileCourse);
printf("Course Has Been Created!\n");
}
void inputDetails(COURSE *c) {
printf("Enter a course number: \n");
scanf("%d", &courseNumber);
printf("Enter a Course Name: \n");
fgets(c->courseName, sizeof(courseName), stdin);
printf("Enter the course schedule (MWF or TR): \n");
fgets(c->courseSched, 4, stdin);
fflush(stdin);
printf("Enter the course credit hours: \n");
scanf("%d",&c->courseHours);
fflush(stdin);
printf("Enter Number of Students Enrolled: \n");
scanf("%d",&c->courseSize);
return;
}
void readCourseRecord(){
COURSE data;
int flag = 0;
int readCourseNumber = 0;
printf("Please Enter a Course Number to Display\n");
scanf("%d", &readCourseNumber);
fflush(stdin);
pfileCourse = fopen("courses.dat", "rb");
while((fread(&data, sizeof(data), 1, pfileCourse)) > 0) {
if(readCourseNumber == courseNumber)
{
display(data);
flag = 1;
}
}
fclose(pfileCourse);
if(flag == 0)
printf("Course not Found!\n");
}
void deleteCourse(){
int newCourseNum;
COURSE data;
FILE *file2;
printf("Please Enter The Course You Wish You Delete\n");
scanf("%d", &newCourseNum);
pfileCourse = fopen("courses.dat", "rb");
file2 = fopen("temp.dat", "wb");
rewind(pfileCourse);
while((fread(&data, sizeof(data), 1, pfileCourse)) > 0)
{
if(courseNumber != newCourseNum)
{
fwrite(&data, sizeof(data), 1, file2);
}
}
fclose(file2);
fclose(pfileCourse);
remove("courses.dat");
rename("temp.dat", "courses.dat");
printf("%d was Successfully deleted\n", newCourseNum);
}
void modifyCourseInfo()
{
COURSE data;
int newCourseNum, found = 0;
printf("Modify\n");
printf("Please Enter The Course You Wish You Modify\n");
scanf("%d", &newCourseNum);
pfileCourse = fopen("courses.dat", "rb+");
while ((fread(&data, sizeof(data), 1, pfileCourse)) > 0 && found == 0)
{
if (courseNumber == newCourseNum)
{
display(data);
printf("Please Enter New Details\n");
inputDetails(&data);
fseek(pfileCourse, - (long)sizeof(data), 1);
fwrite(&data, sizeof(data), 1, pfileCourse);
printf("Course Updated\n");
found == 1;
}
}
fclose(pfileCourse);
if(found == 0)
printf("ERROR: course not found\n");
}
void display(COURSE c){
printf("courseNumber:\t %d\n", courseNumber);
printf("courseName:\t %s\n",c.courseName);
printf("courseSched:\t %s\n",c.courseSched);
printf("courseName:\t %d\n",c.courseHours);
printf("courseSize:\t %d\n",c.courseSize);
}
It doesn't skip courseName, courseName just gets value '\n' because scanf function stops reading your input BEFORE white space. Scanf ignores any whitespace characters encountered before the next non-whitespace character. So you can just add
scanf("%d[^\n]", &courseNumber);
getchar();
after every scanf you have but I'd recommend you to use fgets function for every interactive input.

C issue: Program terminates itself

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
char choice;
struct {
char name[20];
int rn;
}read,write;
void wr(){
FILE *fp;
fp = fopen("record.txt","a+");
printf("Enter Your Name: ");
scanf("%s",write.name);
printf("Enter Your Roll Number: ");
scanf("%d",&write.rn);
fprintf(fp,"%s\t%d",write.name,write.rn);
fclose(fp);
menu();
}
void rd(){
FILE *fp;
fp = fopen("record.txt","r");
while(fscanf(fp,"%s %d",read.name,&read.rn)!= EOF){
printf("%s\t%d\n",read.name,read.rn);
}
fclose(fp);
getche();
menu();
}
void menu(){
system("cls");
printf("Do you want to read/write/exit the data R/W/E: ");
scanf("%c",&choice);
tolower(choice);
if(choice == 'w'){
wr();
}
else if(choice == 'r'){
rd();
}
else if(choice == 'e'){
exit(1);
}
}
int main() {
menu();
getche();
system("cls");
return 0;
}
I want to terminate it when user enters 'e' but it terminates after every information entry as well as I read data.
Means after every time read or write function works and the program should ask again about the choice it terminates.
You need to use a for or a while loop like so:
int main()
{
while(1) // while true
{
menu();
getche();
system("cls");
}
return 0;
}
You are already calling exit(1) in your else if of menu(), so add the while(true) and it will work as you want it to.

dealing with files and structures in c

while i'm working on my manii project phonebook , i faced some problems in delete function when there are multi result for the same first name (i use first name to search about the contact that i want to delete)
in this case i made extra variable in my structure called "ID" and this ID Auto fill in my program (so each user has a unique id) , so i can later find exactly the result that the user want to delete it ,and it works fine , but when i delete a contact from the file it left me with a gap and this effect on the next contact
For Example :
i have 3 contacts each one has an iD 1 , 2 and 3 , when i delete No.2 , it become 1 and 3 , when i add a new user my Auto fill loop will count the number of the contacts (2) and give the new one ID of 3 , that left me with 3 contacts with ID of 1 , 3 , and 3 and this's wrong
so i came with an idea to Reset all the IDs after each Delete operation , it seems good for me and this few line should do it , i don't know why this part doesn't work , even i tried to put this loop in add() function so it should be good at this position too , but it doesn't work too
// reset all ids
rewind(ft);
int id=1;
while(fread(&p,sizeof(p),1,ft)==1)
{
p.id = id;
fwrite(&p,sizeof(p),1,ft);
id++;
}
This is my Full code with 0 Errors and 0 warning , and it work fine except the part of reset ids
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <string.h>
#include <conio.h>
struct address // nested
{
char city[30],
street[30];
int flat;
};
struct phonebook // main
{
int id;
char firstName[20],
lastName[20];
struct address add;
long int phNumber;
char email[50];
};
// functions ...
void launcher();
void menu();
void add();
void load();
void query();
void Delete();
void modify();
void back();
void scan(char *name);
int main()
{
system("color 1e");
printf("Let's start!\n");
launcher();
return 0;
}
void launcher()
{
menu();
}
void back()
{
menu();
}
void menu()
{
system("cls");
printf("\t\t *********** PhoneBook! *************");
printf("\n\n\t\t\t\t <| Menu |>\t\t\n\n");
printf("\t\t1.Add \t2.Load \t3.Query \n\t\t4.Modify \t5.Delete\t6.Exit\n");
switch(getch())
{
case '1' :
add();
break;
case '2' :
load();
break;
case '3' :
query();
break;
case '4' :
modify();
break;
case '5' :
Delete();
break;
case '6' :
printf("the program exit successfully");
exit(0);
break;
default:
system("cls");
int i;
for(i=15 ; i>-1 ; i--)
{
system("cls");
printf("\nInvalid key Entered , please enter any key from 1 to 6 only!\n");
printf("you will back to the main menu automatically in %d seconds",i);
Sleep(1000);
}
menu();
}
}
void add()
{
system("cls");
struct phonebook p; // local define
FILE *f;
f= fopen("data","ab+");
int id=1;
while(fread(&p,sizeof(p),1,f)==1)
{
id++;
}
printf("\nFirst Name : ");
scan(p.firstName);
printf("\nLast Name : ");
scan(p.lastName);
printf("\nEnter the address .. ");
printf("\n\tCity : ");
scan(p.add.city);
printf("\n\tStreet : ");
scan(p.add.street);
printf("\n\tFlat : ");
scanf(" %d",&p.add.flat);
printf("\nPhone number : ");
scanf(" %ld",&p.phNumber);
printf("\nEmail : ");
scan(p.email);
p.id=id; // Auto fill
fwrite(&p,sizeof(p),1,f); // saving the data into a file
fclose(f);
puts("\n\n\t\tdata is saved successfully!");
puts("\t\tEnter any key to back to the main menu");
getch();
back();
}
void load()
{
struct phonebook p;
system("cls");
FILE* f;
f = fopen("data","rb");
if(f==NULL)
{
puts("\n An error occur while opening the file >");
exit(1);
}
while(fread(&p,sizeof(p),1,f)==1)
{
printf("\n\n\t\t\t\t <| loading List |>\t\t\n\n");
printf("First name : %s\nLast name : %s\nAddress Info ...\nCity : %s\nStreet : %s\nFlat : %d\nPhone Number : %ld\nEmail : %s\nid : %d\n",p.firstName,p.lastName,p.add.city,p.add.street,p.add.flat,p.phNumber,p.email,p.id);
puts("\t\t * Enter any key to show more *");
getch();
system("cls");
}
fclose(f);
puts("\t\tno more data to show !");
puts("\t\tEnter any key to back to the main menu");
getch();
back();
}
void query()
{
system("cls");
struct phonebook p;
FILE* f;
f = fopen("data","rb");
if(f==NULL)
{
puts("\n An error occur while opening the file >");
exit(1);
}
char name[50];
int flag=0;
printf("please enter a name : ");
scan(name);
system("cls");
while(fread(&p,sizeof(p),1,f)==1)
{
if(strcmp(name,p.firstName)==0)
{
flag++;
printf("\n[%d] result found\n",flag); // ==> static text
printf("First name : %s\nLast name : %s\nAddress Info ...\nCity : %s\nStreet : %s\nFlat : %d\nPhone Number : %ld\nEmail : %s\n",p.firstName,p.lastName,p.add.city,p.add.street,p.add.flat,p.phNumber,p.email);
puts("");
}
}
if(flag == 0)
{
puts("file not found");
}
fclose(f);
puts("\t\tEnter any key to back to the main menu");
getch();
back();
}
void modify()
{
system("cls");
struct phonebook p,s;
FILE* f;
f = fopen("data","rb+");
if(f==NULL)
{
puts("\n An error occur while opening the file >");
exit(1);
}
char name[50];
int flag=0;
printf("please enter a name : ");
scan(name);
system("cls");
int results[50];
while(fread(&p,sizeof(p),1,f)==1)
{
if(strcmp(name,p.firstName)==0)
{
results[flag] = p.id;
flag++;
printf("\n\n >> full information about the result No. [%d] :- \n",p.id);
printf("First name : %s\nLast name : %s\nAddress Info ...\nCity : %s\nStreet : %s\nFlat : %d\nPhone Number : %ld\nEmail : %s\n",p.firstName,p.lastName,p.add.city,p.add.street,p.add.flat,p.phNumber,p.email);
}
}
if(flag == 0)
{
puts("file not found");
}
else
{
int choice,i,found=0;
int lastResultID = p.id;
puts("Please enter the Number of the result to confirm your order");
scanf(" %d",&choice);
// confirmation
for(i=0 ; i<flag ;i++){
if(results[i] == choice){
found =1;
break;
}
}
if(found == 0){
puts("\n Ops! Result not found.\nmaybe you entered a wrong No. OR an Error occurs Try again.");
Sleep(5000);
back();
}else{
//printf("\n%d\n",lastResultID);
puts("\n >> Are you want to modify this result ? type (Y) for Yes or (N) for No !");
char c = getch();
if( c == 'Y' || c == 'y')
{
system("cls");
printf("\nFirst Name : ");
scan(s.firstName);
printf("\nLast Name : ");
scan(s.lastName);
printf("\nEnter the address .. ");
printf("\n\tCity : ");
scan(s.add.city);
printf("\n\tStreet : ");
scan(s.add.street);
printf("\n\tFlat : ");
scanf(" %d",&s.add.flat);
printf("\nPhone number : ");
scanf(" %ld",&s.phNumber);
printf("\nEmail : ");
scan(s.email);
fseek(f,-sizeof(p)*(lastResultID-choice+1),SEEK_CUR);
s.id=choice;
fwrite(&s,sizeof(p),1,f); // saving
puts("\n\t\tyour data is modified!");
fclose(f);
puts("\t\tEnter any key to back to the main menu");
getch();
back();
}
else
{
system("cls");
puts("nothing change ! , press any key to back to the main menu !");
getch();
back();
}
}
}
}
void Delete()
{
int found =0;
system("cls");
struct phonebook p,s;
FILE* f;
FILE* ft;
f = fopen("data","rb");
ft = fopen("temp","ab+");
if(f == NULL || ft == NULL)
{
puts("\n An error occur while opening the file >");
perror("fopen() failed");
exit(1);
}
char name[50];
int flag=0,i;
int results[50];
printf("please enter a name : ");
scan(name);
system("cls");
while(fread(&p,sizeof(p),1,f)==1)
{
if(strcmp(name,p.firstName)==0)
{
results[flag] = p.id;
flag++;
printf("\n\n >> full information about the result No. [%d] :- \n",p.id);
printf("First name : %s\nLast name : %s\nAddress Info ...\nCity : %s\nStreet : %s\nFlat : %d\nPhone Number : %ld\nEmail : %s\n",p.firstName,p.lastName,p.add.city,p.add.street,p.add.flat,p.phNumber,p.email);
}
}
if(flag == 0)
{
puts("file not found");
}
else{
puts(" ");
int choice,check=0;
puts("please enter the number of the result which you want to delete");
scanf(" %d",&choice);
// confirmation
for(i=0 ; i<flag ;i++){
if(results[i] == choice){
check =1;
break;
}
}
if(check == 0){
puts("\n Oops! Result not found.\nmaybe you entered a wrong No. OR an Error occurred Try again later.");
Sleep(3500);
back();
}else{
puts("\n >> Do you want to delete this result ? type (Y) for Yes or (N) for No !");
char c = getch();
rewind(f); // reset the pointer
if( c == 'Y' || c == 'y')
{
system("cls");
while(fread(&p,sizeof(p),1,f)==1)
{
if(choice != p.id)
fwrite(&p,sizeof(p),1,ft);
if(choice == p.id)
found++;
}
//perror("fread() failed");
if(found == 0)
{
puts("An error occurred , please try again");
remove("temp");
Sleep(3500);
back();
fclose(f); // ==?
fclose(ft); // ==?
}
else
{
// reset all ids
rewind(ft);
int id=1;
while(fread(&p,sizeof(p),1,ft)==1)
{
p.id = id;
fwrite(&p,sizeof(p),1,ft);
id++;
}
fclose(f); // ==?
fclose(ft); // ==?
remove("data");
int c = rename("temp","data");
puts("file is deleted successfully");
if(c != 0)
perror("rename() failed"); // handling for rename error
}
puts("\t\tEnter any key to back to the main menu");
getch();
back();
}
else
{
system("cls");
puts("nothing changed ! , press any key to back to the main menu !");
getch();
back();
}
}
}
/*else
{
puts("\n >> Are you want to delete this result ? type (Y) for Yes or (N) for No !");
char c = getch();
if( c == 'Y' || c == 'y')
{
rewind(f);
while(fread(&p,sizeof(p),1,f)==1)
{
if(strcmp(name,p.firstName)!=0)
fwrite(&p,sizeof(p),1,ft);
}
fclose(f);
fclose(ft);
remove("data");
int c = rename("temp","data");
puts("file is deleted successfully");
if(c != 0)
perror("rename() failed");
// reset all ids
int id=1;
while(fread(&p,sizeof(p),1,f)==1)
{
p.id = id;
fwrite(&p,sizeof(p),1,f);
id++;
}
puts("\t\tEnter any key to back to the main menu");
getch();
back();
}
else
{
system("cls");
puts("nothing change ! , press any key to back to the main menu !");
getch();
back();
}
}*/
}
void scan(char *name)
{
int i=0,j;
char c,ch;
do
{
c=getch();
if(c!=8&&c!=13)
{
*(name+i)=c;
putch(c);
i++;
}
if(c==8)
{
if(i>0)
{
i--;
}
// printf("h");
system("cls");
for(j=0; j<i; j++)
{
ch=*(name+j);
putch(ch);
}
}
}
while(c!=13);
*(name+i)='\0';
}
Thanks in advance
What about using the highest id+1 instead of counting them?
int id = 1;
while(fread(&p,sizeof(p),1,f)==1)
{
if (p.id >= id) id = p.id+1;
}
You cannot interleave fread and fwrite without an intervening fseek:
7.21.5.3/7 When a file is opened with update mode ('+' as the second or third character in the above list of mode argument values), both input and output may be performed on the associated stream. However, output shall not be directly followed by input without an intervening call to the fflush function or to a file positioning function (fseek, fsetpos, or rewind), and input shall not be directly followed by output without an intervening call to a file positioning function, unless the input operation encounters end-of-file.

C read file, struct and infinity loop

I wrote a program that collects user data and saves it to a file. At the moment when he wants to view the file, the program loops and shows only the first record. I do not know what this error is caused.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
FILE *fptr;
struct notification {
char name[50];
char lastname[50];
char price[10];
char descreption[100];
}notification;
void insertRecord()
{
fptr=fopen("G:\\file.txt","a+");
fflush(stdin);
printf("Podaj imie: ");
gets(notification.name);
printf("Podaj nazwisko: ");
gets(notification.lastname);
printf("Podej cene: ");
gets(notification.price);
printf("Podaj opis usterki: ");
gets(notification.descreption);
strcat(notification.descreption,"\n");
if(fwrite(&notification,sizeof(notification),1,fptr) != 1)
{
perror("Blad: ");
} else{
printf("Dane dodane poprawnie\n");
}
fclose(fptr);
}
void readDatabase()
{
struct notification *object2=malloc(sizeof(struct notification));
fptr=fopen("G:\\file.txt","rb");
fread(object2,sizeof(struct notification),1,fptr);
while(!feof(fptr))
{
printf("Imie: %s\n", object2->name);
printf("Nazwisko: %s\n", object2->lastname);
printf("Cena: %s\n", object2->price);
printf("Opis: %s\n", object2->descreption);
printf("==========\n");
}
fclose(fptr);
}
int main() {
int i,option=0,check=0;
do{
printf("1) Dodaj rekord do bazy \n");
printf("2) Odczytaj rekordy z bazy \n");
printf("0) Zakoncz program \n");
scanf("%d", &option);
switch (option)
{
case 1:
insertRecord();
break;
case 2:
readDatabase();
break;
default:
break;
}
}while(check == 0); //petla dziala dopóki zmienna check bedzie równa 0
}
EDIT:
Correct insertRecord function:
void insertRecord()
{
fptr=fopen("G:\\file.txt","a+");
fflush(stdin);
struct notification *obj = malloc(sizeof(struct notification));
printf("Podaj imie: ");
gets(obj->name);
printf("Podaj nazwisko: ");
gets(obj->lastname);
printf("Podej cene: ");
gets(obj->price);
printf("Podaj opis usterki: ");
gets(obj->descreption);
strcat(notification.descreption,"\n");
if(fwrite(obj,sizeof(struct notification),1,fptr) != 1)
{
perror("Blad: ");
} else{
printf("Dane dodane poprawnie\n");
}
free(obj);
fclose(fptr);
}
Now ALL display and insert OK, but in file.txt I see Chinese characters, why?
There are a variety of problems in the readDatabase function
while(!feof)-is-always-wrong
the fread needs to be in the loop.
you don't need to malloc the memory, but if you do malloc memory, you should free it when you're done with it
you always need to check the return value from fopen, because it can and does fail, e.g. because the file is not found
With all that in mind, the readDatabase function should look like this
void readDatabase( void )
{
struct notification object2;
if ( (fptr = fopen("G:\\file.txt","rb")) == NULL )
{
printf( "File not found\n" );
return;
}
while ( fread( &object2, sizeof(struct notification), 1, fptr ) == 1 )
{
printf("Imie: %s\n", object2.name);
printf("Nazwisko: %s\n", object2.lastname);
printf("Cena: %s\n", object2.price);
printf("Opis: %s\n", object2.descreption);
printf("==========\n");
}
fclose(fptr);
}
Move this line:
fread(object2,sizeof(struct notification),1,fptr);
inside your while loop.
scanf("%d", &option); followed by gets() leads to trouble. The first does not consume the '\n' after the number and the second only reads in the short line '\n'.
Do not use scanf(). Do not use gets(). Use fgets(), then parse the input.
scanf() will leave new line character in input stream by default. you can use getchar() function to clear this new line character or you can flush the input buffer like this.
while ((ch = getchar()) != '\n' && ch != EOF);
but don't use fflush(stdin) because if the file stream is for input use, as stdin is, the behaviour is undefined, therefore it is not acceptable to use fflush() for clearing keyboard input. As usual, there are some exceptions, check your compiler's documentation to see if it has a (non-portable) method for flushing input.

Menu not working properly

#include <stdio.h>
#include <stdlib.h> //for the clear screen function
#include <string.h>
struct customer
{
int custID;
char custName[50];
char custAddress[100];
};
typedef struct customer c;
void load_menu(void);
void customers_menu(void);
void createNew(void); //initialize your file
void add_Customer(c c1[30]); //add a new record to the file
FILE *fp;
int main(void)
{
load_menu();
return 0;
}
void load_menu(void)
{
int choice;
do
{
printf("Customer Orders Main Menu. \n\n");
printf("Please enter your choice: \n");
printf("1. Customer's Menu \n");
printf("2. Orders Menu\n");
printf("3. Product Stock Menu\n");
printf("4. Exit\n");
printf("\n");
if (scanf("%d",&choice)==1)
{
switch(choice)
{
case 1: system ("cls");
customers_menu();
printf("\n");
break;
case 2: system ("cls");
orders_menu();
printf("\n");
break;
case 3: system ("cls");
stock_menu();
printf("\n");
break;
case 4: printf("Quitting program!\n");
break;
default: printf("Invalid choice! Please try again\n");
printf("\n");
break;
}
}
else
{
fflush(stdin);
printf("Characters are invalid, please enter a number: \n ");
choice=0;
}
}while((choice !=4));
}
void createNew(void)
{
FILE *fp;
fp=fopen("Customer.dat", "w");
if (fp==NULL)
printf("File creation failed! \n");
else
{
printf("File created! \n");
fclose(fp);
}
}
void add_Customer (c c1[30])
{
int i, n , cc=0;
FILE *fp;
fp=fopen("Customer.dat", "a");
system("cls");
if(fp==NULL)
{
printf("File Creation Failed!");
}
system("cls");
printf("Enter the number of Customers: ");
scanf("%d", &n);
for(i=0;i<n;i++)
{
printf("Customer's ID (numbers only) : ");
scanf("%d", &c1[i].custID);
printf("Customer's Name : ");
gets(c1[i].custName);
printf("Customer's Address : ");
gets(c1[i].custAddress);
fwrite(&c1[i], sizeof(c), 1, fp);
}cc++;
fclose(fp);
}
void recordCount(c c1[30], int *count)
{
add_Customer(c1);
count=0;
count++;
}
void customers_menu(void)
{
int choice;
c c1[30];
int i;
do
{
printf("\n");
printf("Customers Menu \n\n");
printf("Please enter your choice: \n");
printf("1. Add Customer \n");
printf("2.\n");
printf("3.\n");
printf("4. Go back to Main Menu \n");
recordCount (c1, &i);
if (scanf("%d",&choice)==1)
{
switch(choice)
{
case 1: add_Customer(c1);
createNew();
printf("\n");
break;
case 2:
printf("\n");
break;
case 3:
printf("\n");
break;
case 4: printf("Going back to Main Menu\n");
system ("cls");
break;
default: printf("Invalid choice! Please try again\n");
printf("\n");
break;
}
}
else
{
fflush(stdin);
printf("Characters are invalid, please enter a number: \n ");
choice=0;
}
}while((choice !=4));
I have a problem since when I enter the Customers Menu it is staring to execute case 1 immediately (which still doesn't work properly). Can someone help me fix this error please because I tried everything I know and it is still in vain
I think your issue is that in customers_menu() you output the menu, but do not read the selection, instead you call recordCount() which directly calls addCustomer().
After addCustomer() we return the customers_menu() which then calls scanf() for the long gone menu.
A few other notes:
gets() is not good, I suggest you use scanf() (with %s) instead.
Doing a printf() then clearing the screen is a bit pointless.
Error messages should really go to stderr (fprintf(stderr,...)) rather than stdout (printf(...))
You code is a missing trailing }.
cc is added to, but not used.
This problem coming from if (scanf("%d",&choice)==1) because scanf will not return choice. If you enter valid answer (like number), then it returns 1 and switch case work with 1. I think that's the problem.
If you enter char instead of integer, scanf will return 0.

Resources