appending to/reading from text file
ok i have to do a program with a menu, one option is to add a name to the list(in a file), the second part is to list all names added. (a phonebook of sorts)that's the basics, i can write the names to the file fine, but i can't get them to be printed out, i'd appreciate any help.
Quote:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char lname[100000], fname[100000], num[100000];
void entry(void);
void list(void);
int count=0, i=0;
FILE *fptr;
void main()
{
int choice=0, x=0;
fptr=fopen("phonebook.dat", "a+");
if(fptr==NULL){
printf("error");
exit(1);
}
while(x==0){
printf("1.Enter a name and number.\n");
printf("2.List all entries.\n");
printf("3.Exit.\n");
scanf("%d", &choice);
switch(choice){
case 1:
entry();break;
case 2:
list(); break;
case 3:
x=1;
fclose(fptr);break;
}/*end switch*/
}/*end while*/
}/*end main*/
void entry()
{
printf("Enter last name ");
scanf("%s", &lname);
printf("\nEnter first name ");
scanf("%s", &fname);
printf("\nEnter phone number ");
scanf("%s",&num);
fprintf(fptr, "%s, %s, %s\n", lname, fname, num);
}
void list()
{
/****************main problem(i think)******************/
FILE *out_fptr;
char string[100];
out_fptr=fopen("phonebook.dat", "r");
while(!feof(out_fptr)){
fscanf(out_fptr, "%s", &string);
if(feof(out_fptr))break;
printf("%s", string);
}
}
wasn't so sure about the out_fptr, that was just a guess cus it didn't work before
don't touch your that part of your code( list() )... you missed something.
Your problem lies in 'entry()'
----
Code:
void entry()
{
printf("Enter last name ");
scanf("%s", &lname);
printf("\nEnter first name ");
scanf("%s", &fname);
printf("\nEnter phone number ");
scanf("%s",&num);
// You forgot to re- assign 'fptr' ... your in a diff. function
fptr = fopen("phonebook.dat","a"); // add this
if(!fptr)
printf("\n Error : Opening File");
fprintf(fptr, "%s, %s, %s\n", lname, fname, num);
fclose(fptr); // and this
}
And you should take,
Code:
fptr=fopen("phonebook.dat", "a+");
if(fptr==NULL)
{
printf("error");
exit(1);
}
out of main().
weee!
:)