
September 11th, 2012, 09:50 AM
|
|
Registered User
|
|
Join Date: Sep 2012
Posts: 1
Time spent in forums: 46 m 44 sec
Reputation Power: 0
|
|
|
Fprintf and fscanf
Hello everyone! I'm a biginner in C programming and i have a problem with a program in my textbook.It's a phonebook but only the "enter" and "find" functions work.Can anyone tell me why the other two functions "save" and "load" doesn't work ( at least with me). Thanks.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char names[100][40];
char numbers[100][40];
int loc=0;
int menu(void);
void enter(void);
void find(void);
void save(void);
void load(void);
main()
{
int choice;
do{
choice=menu();
switch(choice){
case 1: enter();
break;
case 2: find();
break;
case 3: save();
break;
case 4: load();
break;
}
}while(choice!=5);
return 0;
}
int menu(void)
{
int i;
char str[80];
printf("1.Enter the names and numbers.\n");
printf("2.Find numbers.\n");
printf("3.Save directory to disk.\n");
printf("4.Load directory from disk.\n");
printf("5.Quit.\n");
do{
printf("Enter your choice: ");
gets(str);
i=atoi(str);
printf("\n");
}while(i<1 || i>5);
return i;
}
void enter(void)
{
for(;loc<100;loc++){
if(loc<100){
printf("Enter name and phone number:\n");
gets(names[loc]);
if(!*names[loc]) break;
gets(numbers[loc]);
}
}
}
void find(void)
{
char name[80];
int i;
printf("Enter name:");
gets(name);
for(i=0;i<100;i++)
if(!strcmp(name,names[i]))
printf(" %s %s\n",names[i],numbers[i]);
}
void load(void)
{
FILE *fp;
if((fp=fopen("phone.txt","r"))==NULL){
printf("Cannot open file.\n");
exit(1);
}
loc=0;
while(!feof(fp)){
fscanf(fp,"%s %s",names[loc],numbers[loc]);
loc++;
}
fclose(fp);
}
void save(void)
{
FILE *fp;
int i;
if((fp=fopen("phone","w"))==NULL){
printf("Cannot open file.\n");
exit(1);
}
for(i=0;i<loc;i++){
fprintf(fp, "%s %s", names[i], numbers[i]);
}
fclose(fp);
}
|