Saving read file data into structure

  • (3 Pages)
  • +
  • 1
  • 2
  • 3

37 Replies - 2467 Views - Last Post: 20 November 2012 - 02:05 AM Rate Topic: -----

#1 jcmoney1010  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 21
  • Joined: 03-October 12

Saving read file data into structure

Posted 18 November 2012 - 12:35 AM

I'm able to import the file and read it, but I don't think it's saving to the structure. I want to figure out how to save it within the structure so I can search/ delete the contacts. The unfortunately lengthy code is below:

#include <stdio.h> 
#include <string.h>
#include <stdlib.h>
#include <conio.h>
#define BUFFSIZE 500
//Structure for contacts. These are now pointers.
typedef struct friends_contact{

  char *First_Name;
  char *Last_Name;
  char *home;
  char *cell;
}fr;
//Function declarations 
void menu(fr*friends ,int* counter,int i,char buffer[]);
void setFirst(fr*,int *,int i,char buffer[]);
char getFirst(fr*,int i);
void setLast(fr*friends, int* counter, int i,char buffer[]);
char getLast(fr*friends , int i);
void setHome(fr*friends, int* counter, int i,char buffer[]);
char getHome(fr*friends, int i);
void setCell(fr*friends, int* counter, int i,char buffer[]);
char getCell(fr*friends, int i);
void add_contact(fr*friends,int* counter,int i,char buffer[]);
void print_contact(fr*friends ,int* counter, int i,char user_entry3[50]);
char delete_contact(fr*friends ,int* counter, int i);
int show_contact(fr*friends ,int* counter, int i);
void file(fr*friends ,int* counter, int i,char user_entry3[50]);
void file2 (fr*friends ,int* counter, int i,char buffer[],FILE*read);

int main() 
{
  fr friends[5];
  char buffer[BUFFSIZE];
  int counter=0;
  int i=0;

  menu(friends, &counter,i,buffer);

  getch();
  return 0;
}
//Menu function
void menu(fr*friends,int* counter, int i,char buffer[]) 
{
 int user_entry=0;
 int user_entry1=0;
 int user_entry2=0;
 char user_entry3[50]={'\0'};
 FILE *read;
 printf("Welcome! Would you like to import a file? (1)Yes or (2) No");
 scanf("%d",&user_entry1);
 if(user_entry1==1)
   {
    printf("Please enter a file name");
    scanf("%s",user_entry3); 
    read=fopen(user_entry3,"r");
   }else;

 do{
  int result;

  printf("\nPhone Book Application\n");
  printf("1) Add friend\n2) Delete friend\n3) Show a friend\n4) Show  phonebook\n5)Exit\n");   
  scanf("%d", &user_entry);
if(user_entry==1)
  {
    add_contact(friends,counter,i,buffer);
  }
if(user_entry==2)
  {
    delete_contact(friends ,counter,i);
  } 
if(user_entry==3)
  {
    result=show_contact(friends ,counter,i);
    if(result==0){
                  printf("\nName not Found\n");
                  }else{
                        result;
                        }

 }                  
if(user_entry==4)
 {
   print_contact(friends, counter,i,user_entry3);
   if(user_entry1==1)
     {
   file2(friends ,counter,i,buffer,read);
      }else;
 } 

}while(user_entry!=5);
  if(user_entry==5)
    {
      printf("Would you like to save entries to a file? (1)yes or (2) no");
      scanf("%d",&user_entry2);
      if(user_entry2 == 1)
        {
          printf("Please name your file");
          scanf("%s",user_entry3); 
          file(friends, counter,i,user_entry3);
          printf("Goodbye!"); 

     }else if(user_entry2 == 2)
        {
     printf("Goodbye!"); 
        }

    }

 }
//Start of Set functions. Each entry has its own set function that gathers the data
//For each interaction, we have a buffer and a malloc.
void setFirst(fr*friends, int* counter, int i,char buffer[]) 
{
  printf("Enter a first name \n");
  scanf("%s",buffer);

  friends[*counter].First_Name=malloc(BUFFSIZE*strlen(buffer));
  strcpy(friends[*counter].First_Name, buffer);

}

void setLast(fr*friends, int* counter, int i,char buffer[]) 
{

  printf("Enter a last name \n");
  scanf("%s",buffer);

  friends[*counter].Last_Name=malloc(BUFFSIZE*strlen(buffer));
  strcpy(friends[*counter].Last_Name, buffer);
}
void setHome(fr*friends, int* counter, int i,char buffer[]) 
{

  printf("Enter a home number \n");
  scanf("%s",buffer);

  friends[*counter].home=malloc(BUFFSIZE*strlen(buffer));
  strcpy(friends[*counter].home, buffer);
}
void setCell(fr*friends, int* counter, int i,char buffer[]) 
{

  printf("Enter a cell number \n");
  scanf("%s",buffer);

  friends[*counter].cell=malloc(BUFFSIZE*strlen(buffer));
  strcpy(friends[*counter].cell, buffer);
}
//Start of Get functions. Each function sends the data to the executing function.
char getFirst(fr*friends , int pos) 
{

   printf("%s ", friends[pos].First_Name);
   return *friends[pos].First_Name;
}

char getLast(fr*friends , int pos)
{

   printf("%s\n", friends[pos].Last_Name);
   return *friends[pos].Last_Name;

}

char getHome(fr*friends , int pos) 
{

   printf("(Home) ""%s\n", friends[pos].home);
   return *friends[pos].home;
}

char getCell(fr*friends , int pos) 
{

   printf("(Cell) ""%s\n", friends[pos].cell);
   return *friends[pos].cell;
}
//This function allows for the all the set functions to be added.
void add_contact(fr*friends,int* counter,int i,char buffer[]) 
{
   setFirst(friends,counter,i,buffer); 
   setLast(friends,counter,i,buffer);
   setHome(friends,counter,i,buffer);
   setCell(friends,counter,i,buffer);
   (*counter)++;
}

//This is used to delete a name out of the book.
char delete_contact(fr*friends ,int* counter, int i)
{
   char name_search[50]={'\0'};
   char Delete[5]={'\0'};

   printf("Search by last name\n");
   scanf("%s",name_search);//Name entry
   for(i=0;i<*counter;i++)
      {
       if(strcmp(name_search,friends[i].Last_Name)==0)//Copys over the name entered
         {                                       
          strcpy(friends[i].Last_Name,Delete);
         }
       }
    //Freeing up memory.
    free(friends[i].First_Name);
    free(friends[i].Last_Name);
    free(friends[i].home);
    free(friends[i].cell);   

    printf("\nName(s) has been deleted\n");             
}
//This function prints out all the contact information
void print_contact(fr*friends ,int* counter, int i,char user_entry3[50]) 
{
    for( i = 0; i < *counter; i++)
    if (strlen(friends[i].First_Name) && strlen(friends[i].Last_Name)&&        strlen(friends[i].home)&& strlen(friends[i].cell ))
       {

          getFirst(friends, i);
          getLast(friends, i);
          getHome(friends, i);
          getCell(friends, i);
        }
}
//Displays the contact in which you are searching for.
int show_contact(fr*friends ,int* counter, int i) 
{  
   char name_search2[50]={'\0'};
   int flag=0;
   printf("Please enter a last name\n");
   scanf("%s",name_search2);
   for(i=0;i<*counter;i++)
      {
      //If the name is found, it reaturns the contact info.Now works for duplicate last names.
        if(strcmp(name_search2,friends[i].Last_Name)==0)
          {
             (strlen(friends[i].First_Name) && strlen(friends[i].Last_Name)&& strlen(friends[i].home)&& strlen(friends[i].cell ));

            getFirst(friends, i);
            getLast(friends, i);
            getHome(friends, i);
            getCell(friends, i);
            flag++;
          }
     }         


    return flag;
}    
void file(fr*friends ,int* counter, int i,char user_entry3[5])
{
FILE*fp;
char flag2;
fp=fopen(user_entry3,"w");

for( i = 0; i < *counter; i++)
   {
     if (strlen(friends[i].First_Name) && strlen(friends[i].Last_Name)&&    strlen(friends[i].home)&& strlen(friends[i].cell ))
        {

        fprintf(fp,"\n""%s ",friends[i].First_Name);
        fprintf(fp,"%s ""\n",friends[i].Last_Name);
        fprintf(fp,"<Home>""%s""\n",friends[i].home);
        fprintf(fp,"<Cell>""%s""\n",friends[i].cell);

        }
  }
   fclose(fp);
}

void file2(fr*friends ,int* counter, int i,char buffer[],FILE*read)
{
  fseek(read, 0, SEEK_SET); 

  while (fscanf(read,"%s", buffer) != EOF) 
     {
       friends[*counter].Last_Name=malloc(BUFFSIZE*strlen(buffer));

       strcpy(friends[*counter].Last_Name, buffer);

       printf("%s\n",friends[*counter].Last_Name);

      }

}

I understand the code isn't perfect, and might have a few flaws that aren't related to this question, but I've been trying for a while to figure this issue out. It would be greatly appreciated if someone could help me out !

Is This A Good Question/Topic? 1
  • +

Replies To: Saving read file data into structure

#2 Adak  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 331
  • View blog
  • Posts: 1,168
  • Joined: 01-April 11

Re: Saving read file data into structure

Posted 18 November 2012 - 01:07 AM

Make a little project for this - just code from your program that reads the file, malloc's the memory, and puts the data into the structures, and prints out the structures, then free's the memory.

That's it. Then we can focus on the problem, and not go swimming in this whole program.

Also, post up 5 lines from the file so we can run it and see what's doing. We may not be able to tell just from studying it - I think so, but maybe you have zee cleevaire code, eh? ;)/>

Seriously, we'll find the problem in minutes.

This post has been edited by Adak: 18 November 2012 - 01:08 AM

Was This Post Helpful? 0
  • +
  • -

#3 jimblumberg  Icon User is offline

  • member icon


Reputation: 3845
  • View blog
  • Posts: 11,735
  • Joined: 25-December 09

Re: Saving read file data into structure

Posted 18 November 2012 - 06:56 AM

Is there a reason you are using pointers for all of your structure variables?

Next I suggest you look into some of these warnings and see if they are not part of your problem.

Quote

||=== c_homework, Debug ===|
main.c||In function ‘menu’:|
main.c|58|warning: suggest braces around empty body in an ‘else’ statement [-Wempty-body]|
main.c|80|warning: statement with no effect [-Wunused-value]|
main.c|90|warning: suggest braces around empty body in an ‘else’ statement [-Wempty-body]|
main.c||In function ‘setFirst’:|
main.c|115|warning: unused parameter ‘i’ [-Wunused-parameter]|
main.c||In function ‘setLast’:|
main.c|125|warning: unused parameter ‘i’ [-Wunused-parameter]|
main.c||In function ‘setHome’:|
main.c|134|warning: unused parameter ‘i’ [-Wunused-parameter]|
main.c||In function ‘setCell’:|
main.c|143|warning: unused parameter ‘i’ [-Wunused-parameter]|
main.c||In function ‘print_contact’:|
main.c|215|warning: unused parameter ‘user_entry3’ [-Wunused-parameter]|
main.c||In function ‘show_contact’:|
main.c|239|warning: statement with no effect [-Wunused-value]|
main.c||In function ‘file’:|
main.c|255|warning: unused variable ‘flag2’ [-Wunused-variable]|
main.c||In function ‘file2’:|
main.c|273|warning: unused parameter ‘i’ [-Wunused-parameter]|
main.c||In function ‘delete_contact’:|
main.c|213|warning: control reaches end of non-void function [-Wreturn-type]|
||=== Build finished: 0 errors, 12 warnings ===|



Jim
Was This Post Helpful? 0
  • +
  • -

#4 jcmoney1010  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 21
  • Joined: 03-October 12

Re: Saving read file data into structure

Posted 18 November 2012 - 10:35 AM

View PostAdak, on 18 November 2012 - 01:07 AM, said:

Make a little project for this - just code from your program that reads the file, malloc's the memory, and puts the data into the structures, and prints out the structures, then free's the memory.

That's it. Then we can focus on the problem, and not go swimming in this whole program.

Also, post up 5 lines from the file so we can run it and see what's doing. We may not be able to tell just from studying it - I think so, but maybe you have zee cleevaire code, eh? ;)/>/>

Seriously, we'll find the problem in minutes.


First things first, zee cleevaire code, *woosh* that went right over my head lol. Secondly, i've stripped down the code to about as basic as I can get it. What we have now is the structure, the main, part of the menu, the delete,show, and search functions, and then of course thee actual read function.

#include <stdio.h> 
#include <string.h>
#include <stdlib.h>
#include <conio.h>
#define BUFFSIZE 500
//Structure for contacts. These are now pointers.
typedef struct friends_contact{

   char *First_Name;
   char *Last_Name;
   char *home;
   char *cell;
}fr;
//Function declarations 
void menu(fr*friends ,int* counter,int i,char buffer[]);
void print_contact(fr*friends ,int* counter, int i,char user_entry3[50]);
char delete_contact(fr*friends ,int* counter, int i);
int show_contact(fr*friends ,int* counter, int i);
void file2 (fr*friends ,int* counter, int i,char buffer[],FILE*read);
char printfile(fr*friends ,int* counter);

int main() {


fr friends[5];
char buffer[BUFFSIZE];
int counter=0;
int i=0;

menu(friends, &counter,i,buffer);

getch();
return 0;
}
//Menu function
void menu(fr*friends,int* counter, int i,char buffer[]) {
int user_entry=0;
int user_entry1=0;
int user_entry2=0;
char user_entry3[50]={'\0'};
FILE *read;
printf("Welcome! Would you like to import a file? (1)Yes or (2) No");
scanf("%d",&user_entry1);
if(user_entry1==1)
     {
     printf("Please enter a file name");
     scanf("%s",user_entry3); 
     
     
     read=fopen(user_entry3,"r+");
     
     
     }else;
do{
     int result;

printf("\nPhone Book Application\n");
printf("1) Add friend\n2) Delete friend\n3) Show a friend\n4) Show phonebook\n5)Exit\n");   
scanf("%d", &user_entry);
   


    if(user_entry==2)
    {
        delete_contact(friends ,counter,i);
        } 
        
     if(user_entry==3)
     {
        result=show_contact(friends ,counter,i);
        if(result==0){
                      printf("\nName not Found\n");
                      }else{
                            result;
                            }
       
     }                  
   if(user_entry==4)
   {
       print_contact(friends, counter,i,user_entry3);
       if(user_entry1==1){
        file2(friends ,counter,i,buffer,read);
        
        }else;
   } 
    
   }while(user_entry!=5);
}

//This is used to delete a name out of the book.
char delete_contact(fr*friends ,int* counter, int i)
{
    char name_search[50]={'\0'};
    char Delete[5]={'\0'};

    printf("Search by last name\n");
    scanf("%s",name_search);//Name entry

    for(i=0;i<*counter;i++)
     {
     
        if(strcmp(name_search,friends[i].Last_Name)==0)//Copys over the name entered
        {
                                                             
          strcpy(friends[i].Last_Name,Delete);
          
           
           
           }
         }
            //Freeing up memory.
                
                free(friends[i].Last_Name);
               
    
  printf("\nName(s) has been deleted\n");             
}
//This function prints out all the contact information
void print_contact(fr*friends ,int* counter, int i,char user_entry3[50]) {

for( i = 0; i < *counter; i++)
  if (strlen(friends[i].First_Name) && strlen(friends[i].Last_Name)&& strlen(friends[i].home)&& strlen(friends[i].cell ))
    {
            
            
            
           
            
    }
}
//Displays the contact in which you are searching for.
int show_contact(fr*friends ,int* counter, int i) 
{  
     char name_search2[50]={'\0'};
     int flag=0;
     printf("Please enter a last name\n");
     scanf("%s",name_search2);
     
         
     for(i=0;i<*counter;i++)
     {
         
    //If the name is found, it reaturns the contact info.Now works for duplicate last names.
     if(strcmp(name_search2,friends[i].Last_Name)==0)
       {
                                                    
        (strlen(friends[i].First_Name) && strlen(friends[i].Last_Name)&& strlen(friends[i].home)&& strlen(friends[i].cell ));
        }   

       }
}
void file2(fr*friends ,int* counter, int i,char buffer[],FILE*read)
{
   fseek(read, 0, SEEK_SET); 
     
    while (fscanf(read,"%s", buffer) != EOF) {
           

   friends[*counter].Last_Name=malloc(BUFFSIZE*strlen(buffer));

   strcpy(friends[*counter].Last_Name, buffer);

   printfile(friends ,counter);
   }
}
char printfile(fr*friends ,int* counter)
{
printf("%s\n",friends[*counter].Last_Name);
}



My file reads
 
 John Smith
<Home>8
<Cell> 9
 


Obviously in order to search and delete this contact, I need it to be saved to the structure so I can treat it like the rest of the contacts that may be entered in later via the program itself. If you can help stop my frustration, you will be my new favorite person. Maybe you have zee cleeevair code?..Ok, I won't try that again, it's just dumb when i say it lol.
Was This Post Helpful? 0
  • +
  • -

#5 jimblumberg  Icon User is offline

  • member icon


Reputation: 3845
  • View blog
  • Posts: 11,735
  • Joined: 25-December 09

Re: Saving read file data into structure

Posted 18 November 2012 - 10:49 AM

In the following snippet:
   if(user_entry==4)
   {
       print_contact(friends, counter,i,user_entry3);
       if(user_entry1==1){
        file2(friends ,counter,i,buffer,read);
        
        }else;
   } 


Please explain the purpose of the else??? If you don't need the else then don't put it there. Not every if statement requires an else statement.

Next start simpler. Start by opening the file in main and then write a function, called from main() that reads your file and fills in your array of structures. Then print each array element to insure you properly read the file. I would also start with static C-string sizes in your structure.

typedef struct friends_contact{

  char First_Name[50];
  char Last_Name[50];
  char home[50];
  char cell[20];
}fr;



Once you are sure you are properly reading your file and filling in your structure then you can move on to the rest of the program.

Jim
Was This Post Helpful? 0
  • +
  • -

#6 Adak  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 331
  • View blog
  • Posts: 1,168
  • Joined: 01-April 11

Re: Saving read file data into structure

Posted 18 November 2012 - 11:44 AM

I want to change this sample around a bit. Basically, I want your code to either:

1) make a BIG array of structs, and use it.

or

2) count the contacts in the phonebook file, and malloc that amount of number of structs for the array of structs. Then rewind the file, and read in the data.

I have to get off the net because a big work unit is about to send in results to Folding@Home. I'll be back when it's done sending (about 35 minutes).

@Jim: This is just a stub of the program. Ignore the else.

This post has been edited by Adak: 18 November 2012 - 11:45 AM

Was This Post Helpful? 0
  • +
  • -

#7 jcmoney1010  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 21
  • Joined: 03-October 12

Re: Saving read file data into structure

Posted 18 November 2012 - 03:01 PM

View PostAdak, on 18 November 2012 - 11:44 AM, said:

I want to change this sample around a bit. Basically, I want your code to either:

1) make a BIG array of structs, and use it.

or

2) count the contacts in the phonebook file, and malloc that amount of number of structs for the array of structs. Then rewind the file, and read in the data.

I have to get off the net because a big work unit is about to send in results to Folding@Home. I'll be back when it's done sending (about 35 minutes).

@Jim: This is just a stub of the program. Ignore the else.


That's cool, I won't be by a computer until later tonight anyway. Thanks for all your help in advance!
Was This Post Helpful? 0
  • +
  • -

#8 jcmoney1010  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 21
  • Joined: 03-October 12

Re: Saving read file data into structure

Posted 18 November 2012 - 09:17 PM

View PostAdak, on 18 November 2012 - 11:44 AM, said:

I want to change this sample around a bit. Basically, I want your code to either:

1) make a BIG array of structs, and use it.

or

2) count the contacts in the phonebook file, and malloc that amount of number of structs for the array of structs. Then rewind the file, and read in the data.

I have to get off the net because a big work unit is about to send in results to Folding@Home. I'll be back when it's done sending (about 35 minutes).

@Jim: This is just a stub of the program. Ignore the else.


Hey were you ever able to take another look at that code sample?
Was This Post Helpful? 0
  • +
  • -

#9 Adak  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 331
  • View blog
  • Posts: 1,168
  • Joined: 01-April 11

Re: Saving read file data into structure

Posted 18 November 2012 - 09:55 PM

I did, and I agree with Jim that having 4 pointers for your struct members, makes it an unholy mess for malloc'ing and free'ing memory for every single friend. A fixed array for them may waste some small amount of memory, but it's a smart trade off.

I'm doing a video "database", that's similar to your program, and chose these same fixed fields, for my own program. Starts off with some defines, and the struct prototype, and then uses a global array (but you can use local if you like) of those structs:

#define MAXTITLE 77
#define MAXACTOR 78
#define MAXGENRA 50
#define MAXVIDS 1000

struct video {
   char title[MAXTITLE];
   char actor[MAXACTOR];
   char genra[MAXGENRA];
   int  rating;          //1-5 stars
};
typedef struct video vid;

vid videos[MAXVIDS];   //the global array of structs
int NumVideos;         //a number used by every function 



The array of structs is large, but the program only works from 0 to NumVideos. Records that you want deleted are not overwritten by shuffling all the other records with a higher index downward. Instead, it just writes out a new file, with only active records in it.

If you adapt a program like this, I believe you'll be FAR less frustrated with it.

There are many of these "flat file" database programs around, btw. They are a common assignment in CS courses (where the subject is usually a student database). Little tricks like a binary search and fast sorter, add a nice touch. A bigger nicety is having the display organized so records can be displayed without having to re-write the menu, with nothing being "torn up" or out of place. Add colored text and a colored background to it, and it starts to look pretty sharp indeed for a console program.
Was This Post Helpful? 0
  • +
  • -

#10 jcmoney1010  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 21
  • Joined: 03-October 12

Re: Saving read file data into structure

Posted 18 November 2012 - 11:44 PM

View PostAdak, on 18 November 2012 - 09:55 PM, said:

I did, and I agree with Jim that having 4 pointers for your struct members, makes it an unholy mess for malloc'ing and free'ing memory for every single friend. A fixed array for them may waste some small amount of memory, but it's a smart trade off.

I'm doing a video "database", that's similar to your program, and chose these same fixed fields, for my own program. Starts off with some defines, and the struct prototype, and then uses a global array (but you can use local if you like) of those structs:

#define MAXTITLE 77
#define MAXACTOR 78
#define MAXGENRA 50
#define MAXVIDS 1000

struct video {
   char title[MAXTITLE];
   char actor[MAXACTOR];
   char genra[MAXGENRA];
   int  rating;          //1-5 stars
};
typedef struct video vid;

vid videos[MAXVIDS];   //the global array of structs
int NumVideos;         //a number used by every function 



The array of structs is large, but the program only works from 0 to NumVideos. Records that you want deleted are not overwritten by shuffling all the other records with a higher index downward. Instead, it just writes out a new file, with only active records in it.

If you adapt a program like this, I believe you'll be FAR less frustrated with it.

There are many of these "flat file" database programs around, btw. They are a common assignment in CS courses (where the subject is usually a student database). Little tricks like a binary search and fast sorter, add a nice touch. A bigger nicety is having the display organized so records can be displayed without having to re-write the menu, with nothing being "torn up" or out of place. Add colored text and a colored background to it, and it starts to look pretty sharp indeed for a console program.


Unfortunately this is for a class, and one of the requirements was that we use pointers within the structure, so I can't deviate from that. I have the entire assignment working, except for this small little issue and it's driving me nuts. I've seem just about every "flat file" database example on google over the last 2-3 days, but have yet to be able to figure out this problem. Oh well, heres to another loooooong night. Thanks for your help though.
Was This Post Helpful? 0
  • +
  • -

#11 Adak  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 331
  • View blog
  • Posts: 1,168
  • Joined: 01-April 11

Re: Saving read file data into structure

Posted 19 November 2012 - 12:27 AM

Oh, well, OK, let me see what I can do to assist on that. I thought this was a personal project - not sure why.

I'll be back, but this is not my forte in programming, to be sure.
Was This Post Helpful? 0
  • +
  • -

#12 jcmoney1010  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 21
  • Joined: 03-October 12

Re: Saving read file data into structure

Posted 19 November 2012 - 12:41 AM

View PostAdak, on 19 November 2012 - 12:27 AM, said:

Oh, well, OK, let me see what I can do to assist on that. I thought this was a personal project - not sure why.

I'll be back, but this is not my forte in programming, to be sure.


Awesome, I'll be here all night lol. I appreciate you working to help me out.
Was This Post Helpful? 0
  • +
  • -

#13 Adak  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 331
  • View blog
  • Posts: 1,168
  • Joined: 01-April 11

Re: Saving read file data into structure

Posted 19 November 2012 - 01:51 AM

This reads the file, malloc's the lastname and first name (which I always call lname and fname, btw). and reads the names into a temp struct, and then over to friends[counter].

/*
John Smith
<Home> 8
<Cell> 9
Sue Dyer
<Home> 3
<Cell> 2
Claire Barton
<Home> 1
<Cell> 5
Rob Clearsky
<Home> 4
<Cell> 6
Billy Bestfriend
<Home> 7
<Cell> 10
*/
#include <stdio.h> 
#include <string.h>
#include <stdlib.h>
#include <conio.h>
#define BUFFSIZE 500
//Structure for contacts. These are now pointers.
typedef struct friends_contact{

   char *fname;
   char *lname;
   char *home;
   char *cell;
}fr;
//Function declarations 
/*
In these functions, if you aren't going to change the counter, you should not have a 
pointer to counter. After you send a pointer to a function, if you subsequently call 
another function (like printfile), send the *counter - because that is NOT a pointer, anymore.
That's the number.
*/

void menu(fr*friends ,int* counter,int i,char buffer[]);
void print_contact(fr*friends ,int* counter, int i,char user_entry3[50]);
char delete_contact(fr*friends ,int* counter, int i);
int show_contact(fr*friends ,int* counter, int i);
void readFile (fr*friends ,int* counter, int i,char buffer[],FILE*read);
char printfile(fr*friends ,int counter);

int main() {

   fr friends[5];
   char buffer[BUFFSIZE];
   int counter=0;
   int i=0;

   menu(friends, &counter,i,buffer);

   //getch();
   return 0;
}
//Menu function
void menu(fr*friends,int* counter, int i,char buffer[]) {
   int user_entry=0;
   int user_entry1=0;
   int user_entry2=0;
   char user_entry3[50]={"phonebook.txt"};
   FILE *fpIn;
   fpIn=fopen(user_entry3,"r+"); //you have to have some data in the phonebook
   //printf("Welcome! Would you like to import a file? (1)Yes or (2) No");
   //scanf("%d",&user_entry1);
   readFile(friends ,counter, i,buffer,fpIn);
   do{
      int result;

      printf("\nPhone Book Application\n");
      printf("1) Add friend\n2) Delete friend\n3) Show a friend\n4) Show phonebook\n5)Exit\n");   
      scanf("%d", &user_entry);
   
      if(user_entry==2)
      {
         delete_contact(friends ,counter,i);
      } 
        
      if(user_entry==3)
      {
         result=show_contact(friends ,counter,i);
         if(result==0){
            printf("\nName not Found\n");
         }else{
            result;
         }
       
      }                  
      if(user_entry==4)
      {
         print_contact(friends, counter,i,user_entry3);
         if(user_entry1==1){
            readFile(friends ,counter,i,buffer,fpIn);
         }else;
      } 
    
   }while(user_entry!=5);
   
}

//This is used to delete a name out of the book.
char delete_contact(fr*friends ,int* counter, int i)
{
   char name_search[50]={'\0'};
   char Delete[5]={'\0'};

   printf("Search by last name\n");
   scanf("%s",name_search);//Name entry

   for(i=0;i<*counter;i++)
   {
      if(strcmp(name_search,friends[i].lname)==0)//Copys over the name entered
      {
         strcpy(friends[i].lname,Delete);
      }
   }
   //Freeing up memory.
   free(friends[i].lname);
   printf("\nName(s) has been deleted\n");
   return 'a';             
}
//This function prints out all the contact information
void print_contact(fr*friends ,int* counter, int i,char user_entry3[50]) {
   for( i = 0; i < *counter; i++)
      if (strlen(friends[i].fname) && strlen(friends[i].lname)&& strlen(friends[i].home)&& strlen(friends[i].cell ))
      {
      }
}
//Displays the contact in which you are searching for.
int show_contact(fr*friends ,int* counter, int i) 
{  
   char name_search2[50]={'\0'};
   int flag=0;
   printf("Please enter a last name\n");
   scanf("%s",name_search2);
     
         
   for(i=0;i<*counter;i++)
   {
      //If the name is found, it reaturns the contact info.Now works for duplicate last names.
      if(strcmp(name_search2,friends[i].lname)==0)
      {  /*for alignment, structs are padded. You can't add up struct members and say that will always be the size
         of the struct - use sizeof(nameOfStruct), in the function you create the struct instance 
         Also, different PC's may give a struct a different size because they use different padding. 
         but sizeof(struct) will be accurate on all. */
         
         //(strlen(friends[i].fname) && strlen(friends[i].lname)&& strlen(friends[i].home)&& strlen(friends[i].cell );
         printf("%s %s %s \n",friends[i].fname,friends[i].lname,friends[i].home,friends[i].cell);  
         flag=1;
      }   
   }
   if(!flag)
      printf("Name not found\n");
   return flag;
}
void readFile(fr*friends ,int* counter, int i,char buffer[],FILE*fpIn)
{
   int j=0;
   fr temp;
   
   //fseek(read, 0, SEEK_SET); 
   while (fscanf(fpIn,"%[^\n]", buffer) != EOF) {
      printf("%s\n",buffer); getchar();
      while(buffer[j++] != ' ');    //note the semi-colon

      temp.fname=malloc(j);
      temp.lname=malloc(strlen(buffer)-j);

      sscanf(buffer,"%s %s",temp.fname,temp.lname);
      //printf("**%s \n%s\n",temp.fname, temp.lname); getchar();
      friends[*counter]=temp;

      printfile(friends ,*counter);
   }
   fclose(fpIn);
   free(temp.lname);
   free(temp.fname);
}
char printfile(fr*friends ,int counter)
{
   printf("%d. %s\n",counter,friends[counter].lname);
   return 'a';
}

Not as polished as I'd like, but it works for that part. Next problem is what? Read in the rest of the data maybe?
I am here for a couple hours, anyway.



Was This Post Helpful? 1
  • +
  • -

#14 jcmoney1010  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 21
  • Joined: 03-October 12

Re: Saving read file data into structure

Posted 19 November 2012 - 02:11 AM

View PostAdak, on 19 November 2012 - 01:51 AM, said:

This reads the file, malloc's the lastname and first name (which I always call lname and fname, btw). and reads the names into a temp struct, and then over to friends[counter].

/*
John Smith
<Home> 8
<Cell> 9
Sue Dyer
<Home> 3
<Cell> 2
Claire Barton
<Home> 1
<Cell> 5
Rob Clearsky
<Home> 4
<Cell> 6
Billy Bestfriend
<Home> 7
<Cell> 10
*/
#include <stdio.h> 
#include <string.h>
#include <stdlib.h>
#include <conio.h>
#define BUFFSIZE 500
//Structure for contacts. These are now pointers.
typedef struct friends_contact{

   char *fname;
   char *lname;
   char *home;
   char *cell;
}fr;
//Function declarations 
/*
In these functions, if you aren't going to change the counter, you should not have a 
pointer to counter. After you send a pointer to a function, if you subsequently call 
another function (like printfile), send the *counter - because that is NOT a pointer, anymore.
That's the number.
*/

void menu(fr*friends ,int* counter,int i,char buffer[]);
void print_contact(fr*friends ,int* counter, int i,char user_entry3[50]);
char delete_contact(fr*friends ,int* counter, int i);
int show_contact(fr*friends ,int* counter, int i);
void readFile (fr*friends ,int* counter, int i,char buffer[],FILE*read);
char printfile(fr*friends ,int counter);

int main() {

   fr friends[5];
   char buffer[BUFFSIZE];
   int counter=0;
   int i=0;

   menu(friends, &counter,i,buffer);

   //getch();
   return 0;
}
//Menu function
void menu(fr*friends,int* counter, int i,char buffer[]) {
   int user_entry=0;
   int user_entry1=0;
   int user_entry2=0;
   char user_entry3[50]={"phonebook.txt"};
   FILE *fpIn;
   fpIn=fopen(user_entry3,"r+"); //you have to have some data in the phonebook
   //printf("Welcome! Would you like to import a file? (1)Yes or (2) No");
   //scanf("%d",&user_entry1);
   readFile(friends ,counter, i,buffer,fpIn);
   do{
      int result;

      printf("\nPhone Book Application\n");
      printf("1) Add friend\n2) Delete friend\n3) Show a friend\n4) Show phonebook\n5)Exit\n");   
      scanf("%d", &user_entry);
   
      if(user_entry==2)
      {
         delete_contact(friends ,counter,i);
      } 
        
      if(user_entry==3)
      {
         result=show_contact(friends ,counter,i);
         if(result==0){
            printf("\nName not Found\n");
         }else{
            result;
         }
       
      }                  
      if(user_entry==4)
      {
         print_contact(friends, counter,i,user_entry3);
         if(user_entry1==1){
            readFile(friends ,counter,i,buffer,fpIn);
         }else;
      } 
    
   }while(user_entry!=5);
   
}

//This is used to delete a name out of the book.
char delete_contact(fr*friends ,int* counter, int i)
{
   char name_search[50]={'\0'};
   char Delete[5]={'\0'};

   printf("Search by last name\n");
   scanf("%s",name_search);//Name entry

   for(i=0;i<*counter;i++)
   {
      if(strcmp(name_search,friends[i].lname)==0)//Copys over the name entered
      {
         strcpy(friends[i].lname,Delete);
      }
   }
   //Freeing up memory.
   free(friends[i].lname);
   printf("\nName(s) has been deleted\n");
   return 'a';             
}
//This function prints out all the contact information
void print_contact(fr*friends ,int* counter, int i,char user_entry3[50]) {
   for( i = 0; i < *counter; i++)
      if (strlen(friends[i].fname) && strlen(friends[i].lname)&& strlen(friends[i].home)&& strlen(friends[i].cell ))
      {
      }
}
//Displays the contact in which you are searching for.
int show_contact(fr*friends ,int* counter, int i) 
{  
   char name_search2[50]={'\0'};
   int flag=0;
   printf("Please enter a last name\n");
   scanf("%s",name_search2);
     
         
   for(i=0;i<*counter;i++)
   {
      //If the name is found, it reaturns the contact info.Now works for duplicate last names.
      if(strcmp(name_search2,friends[i].lname)==0)
      {  /*for alignment, structs are padded. You can't add up struct members and say that will always be the size
         of the struct - use sizeof(nameOfStruct), in the function you create the struct instance 
         Also, different PC's may give a struct a different size because they use different padding. 
         but sizeof(struct) will be accurate on all. */
         
         //(strlen(friends[i].fname) && strlen(friends[i].lname)&& strlen(friends[i].home)&& strlen(friends[i].cell );
         printf("%s %s %s \n",friends[i].fname,friends[i].lname,friends[i].home,friends[i].cell);  
         flag=1;
      }   
   }
   if(!flag)
      printf("Name not found\n");
   return flag;
}
void readFile(fr*friends ,int* counter, int i,char buffer[],FILE*fpIn)
{
   int j=0;
   fr temp;
   
   //fseek(read, 0, SEEK_SET); 
   while (fscanf(fpIn,"%[^\n]", buffer) != EOF) {
      printf("%s\n",buffer); getchar();
      while(buffer[j++] != ' ');    //note the semi-colon

      temp.fname=malloc(j);
      temp.lname=malloc(strlen(buffer)-j);

      sscanf(buffer,"%s %s",temp.fname,temp.lname);
      //printf("**%s \n%s\n",temp.fname, temp.lname); getchar();
      friends[*counter]=temp;

      printfile(friends ,*counter);
   }
   fclose(fpIn);
   free(temp.lname);
   free(temp.fname);
}
char printfile(fr*friends ,int counter)
{
   printf("%d. %s\n",counter,friends[counter].lname);
   return 'a';
}

Not as polished as I'd like, but it works for that part. Next problem is what? Read in the rest of the data maybe?
I am here for a couple hours, anyway.




Amazing, give me a couple mins to implement it and test it and I'll let you know! If this works, you might just be my new best friends lol.
Was This Post Helpful? 0
  • +
  • -

#15 Adak  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 331
  • View blog
  • Posts: 1,168
  • Joined: 01-April 11

Re: Saving read file data into structure

Posted 19 November 2012 - 02:16 AM

I didn't do the home and cell struct members. They're more of the same logic.
Was This Post Helpful? 1
  • +
  • -

  • (3 Pages)
  • +
  • 1
  • 2
  • 3