Welcome to HBH! If you have tried to register and didn't get a verification email, please using the following link to resend the verification email.

C project. picking your brains


ghost's Avatar
0 0

For those that program in c what would be a decent way to make a phone book. How should I design my code so that users will be able to search for the numbers after they enter them. Im not asking for you to write code for me Im just not sure how to do it. I wrote some code but I think I am screwed because I think I should have written it differentl. Now I think I may need to rewrite the enitire thing. Here is the code I have so far.

#include <stdio.h>
#define L1             "##############################################"
#define Name           "#            K P D                           #"          
#define Author         "#      Written by: Knutrainer                #"          
#define Date           "#          9/23/06                           #"          
#define L2             "##############################################"



int menu();
int search();
int list_all();
int add();
int delete();
int edit_name();
int quit();


int main()
{
    system("color a");
    
    printf("\t \n %s \t \n %s \t \n %s \t \n %s \t \n %s", L1,Name,Author,Date,L2); // prints out program information
    
    menu();  //calls my menu function
    
    
return 0;   
}


int menu()
{
     int searchz = 1;  //The reason the letter z was added to the end of these
     int list_allz=2;  //variables was it was conflicting with my functions
     int addz = 3;     //took me an hour to figure out the problem
     int deletez = 4;
     int edit_namez =5;
     int quitz=6;
     int menuz=7;
     int option;
     
      
     printf("\n1: Search\n");//this whole thing prints the users options
     printf("2: List all\n");
     printf("3: Add names\n");
     printf("4: Delete\n");
     printf("5: Edit names\n");
     printf("6: Quit\n");
     printf("\nPlease select an option:");
     
     scanf("%d",&option);  //gets and stores the users options so we can use the switch statment
     
  
     switch(option)   //switches to the users selected option
         {
                   
                  
                   case 1 : search();  //depending on user input a funtion will be executed
                    break;
                   case 2 : list_all();
                   break;
                   case 3 : add();
                   break;
                   case 4 : delete();
                   break;
                   case 5 : edit_name();
                   break;
                   case 6 : quit();
                   break;
                   case 7 : menu();
                   break;
                   default: printf("Invalid input");
                   // add a check to see if input is a number
                    
                   if(option < 1) // if less than 1 go to menu
                         {
                             menu();
                         } 
                   else if(option > 8)   // if more than 7 go to the menu
                         {
                                  menu(); 
                         } 
                   if(!isdigit(option))  // makes sure that input is a digit
                        {
                             printf("\nPlease enter a digit");          
                             menu();   
                        } 
                   
         }
         
}


int search()
{
     FILE *search_ptr;
     search_ptr= fopen("phone_list","r");
     char search_name;
     printf("Please type the last name of the person you are looking for: ");
     
     getch();
     
}

int list_all()
{
    char cont;
    FILE *all_ptr;  //delcaring file pointer for listing all the data in the file
    
    char phone_directory[20000]; // this will store the phone dirs information
    all_ptr = fopen("phone_list.txt","r"); // opens phone_list for reading
    if(all_ptr != NULL)
         {
                while(1)
                      {
                             cont = fgetc(all_ptr); //read the text
                             if(cont!=EOF) //dont stop untill end of file
                                  {
                                          printf("%c",cont);
                                  }
                             else 
                             {
                                  menu();
                             }
                      }
                      
         }
    else
         {
                printf("Unable to retrieve date!");
         }
         
    printf("Data retrieved successfully!\n");
    
    printf("\nPress any key when you want to return to the menu.\n");
    getch();
    menu();
    
    
    
    
     
     
}

int add()
{
    
     char lastname[20] = "    "; // The reasone blank spaces are here is to
     char firstname[20]= "    "; // make sure that if no data is input it wont
     char home_num[15] = "    ";// interfere with my text formating.
     char cell_num[15] = "    ";
     char spaces[10]   = "    ";
     char new_line[10]  = "\n";
     
     char lastz[15] = "Lastname: ";
     char firstz[15] = "Firstname: ";
     char homez[15] = "Home: ";
     char cellz[15] = "Cell: ";
     
    
     printf("\nThis is the add name function. Please follow the prompts.\n");
     printf("If information is unknown please leave blank.");
     
     
     printf("\nPlease enter the last name of the person: ");
     gets(lastname); //I know this looks retarded but for some reason when I only had one here Gets() didnt seem to work
     gets(lastname); // I added this second one and the it started working again. I spent 3 hours on this and had to go with this dirty solution.
     
     printf("Please enter the first name of the person: ");
     gets(firstname);
      
     printf("Please enter the persons home phone number: ");
     gets(home_num);
      
     printf("Please enter the persons cell phone number: ");
     gets(cell_num);
 
     
     
     
     FILE *file_ptr; //Getting ready to write to the file that will store all the information.
     
     file_ptr =fopen("phone_list.txt", "a");
     
     if(file_ptr !=NULL)
            {
                 printf("Name saved!\n");
                 fputs(lastz,file_ptr);
                 fputs(lastname,file_ptr);
                 fputs(spaces,file_ptr);
                 fputs(firstz,file_ptr);
                 fputs(firstname,file_ptr);// make sure to add info to file
                 fputs(spaces,file_ptr); //spaces out the data
                 fputs(homez,file_ptr);
                 fputs(home_num,file_ptr);
                 fputs(spaces,file_ptr);
                 fputs(cellz,file_ptr);
                 fputs(cell_num,file_ptr);
                 fputs(new_line,file_ptr);
                 
                 fclose(file_ptr); //closing file
                 
            }
     else 
         {
             printf("File ERROR! Unable to save!\n");
         }
         
         
      menu();    
     
     
     
     
}

int delete()
{
     printf("testing delete function");
     
}

int edit_name()
{
     printf("testing edit_name function");
     
}

int quit()
{
     return 0;
     
}
     
     
         
     
     
     
    
    
    
                   
               

//Edit by The_Flash - Disabled smileys!


ghost's Avatar
0 0

First of all, this code:

{
menu();
}
else if(option > 8) // if more than 7 go to the menu
{
menu();
}```
can be changed to this:
```markupif(option < 1 || option > 8) // if less than 1 go to menu
menu();```

I noticed that these variables declared in the menu() function are not used anywhere else in the program and simply request unnecessary space on the stack:
```markup int searchz = 1; //The reason the letter z was added to the end of these
int list_allz=2; //variables was it was conflicting with my functions
int addz = 3; //took me an hour to figure out the problem
int deletez = 4;
int edit_namez =5;
int quitz=6;
int menuz=7;```

Also, it seems only the quit() function returns an integer, so the other functions should be of type void. Lastly, it would help to see the format of the phone book file that the program would be searching in. An example file would be best.

ghost's Avatar
0 0

As far as the unneccessary variables I couldnt get it to work any other way. I look into though. Also the user creats the phone book through the add function. Any help for the original problem?


ghost's Avatar
0 0

Hope this helps:

(here's a link to the source files, since HBH fucks up the formating..)

   compile: gcc.exe phone_number.c -o phone_number.exe
*/

#include <stdio.h>

#define BUFFER_SIZE 1024
#define FILE_PATH "c:\\users\\dw0rek\\info.txt" /* the path and file name for the file that will contain all the stored information. */
#define BACKUP_DIR "c:\\users\\dw0rek\\info_backup.txt" /* this is the name and path for the file which will be used to store an exact copy of the
                                                               information file, or rather how it looked like before the remove_info() function was
                                                               used. there will be an option if the backup should be deleted or not. */

int add_info(char *, char *, char *, char *, FILE *); /* the function that adds new user information to the information storeage file. */
int str_input(char *, FILE *); /* used by the add_info() function, this will do the actuall file input. can be used by other functions, but note the
                                  limit that is set to BUFFER_SIZE. */
int read_all(FILE *); /* very simply function that will display all the saved information. */
int search_name(FILE *, char *); /* the search function. will compare the name or number passed to the function through the command line **argv
                                    (-s & -r options), returns the line number of the row that it found the name or number at, if no match was found it
                                    returns -1 */
int string_compare(char *, char *); /* strcmp, why i added this function is so that it would be easy to configure the function if later needed in the
                                       program. personal preferances, just how i like to do it. */
int string_length(char *); /* strlen, same reason */
int read_name(FILE *, int); /* used by the search_name() function. this is what actually prints out the info for the search. */
int remove_info(FILE *, int, char *);


int main(int argc, char **argv)
{
   char program_info[BUFFER_SIZE];
   sprintf(program_info, "Useage:\n"
                         "%s [-a] [-r[[ ]info]] [-s[[ ]info]] [-v]\n"
                         "  -a          Add info.\n"
                         "  -r          Remove info.\n"
                         "  info         Name or number you want to remove\n"
                         "  y/n          y if you want to keep a backup of the file, n othervise\n"
                         "  -s          Search for name or number.\n"
                         "  info         Name or number you want to search for\n"
                         "  -v          View all saved info.\n\n"
                         "Examples:\n"
                         " %s -a\n"
                         "    * Add info that is to be stored in the information file.\n"
                         " %s -r unwanted_user y\n"
                         "    * Removes \"unwanted_user\" from the information file, and keeps to backup\n"
                         " %s -s forgotten_user\n"
                         "    * searches for \"forgotten_user\" and displays the information about the user, if found.\n"
                         " %s -v\n"
                         "    * displays all saved information.\n\n", *argv, *argv, *argv, *argv, *argv);
   if(argc < 2 || argc > 4)
   {
      fprintf(stderr, "%s", program_info);
      return 1;
   }
   FILE *f_w;
   char first_name[BUFFER_SIZE], last_name[BUFFER_SIZE], home_number[BUFFER_SIZE], mobile_number[BUFFER_SIZE], option;
   int line_number;
   if(string_compare(*(argv + 1), "-a") >= 0)
   {
      add_info(first_name, last_name, home_number, mobile_number, f_w);
   }
   else if(string_compare(*(argv + 1), "-r") >= 0 && argc == 4)
   {
      if((line_number = search_name(f_w, *(argv + 2))) < 0) /* change the if statment to a while loop if you want the remove function to be recursive
                                                               and delete _every_ name or number that matches. the same thing can easily be done with
                                                               the call to the search function, to make the search recursive so that it covers every
                                                               match. */
      {
         printf("Not found.\n");
      }
      else
      {
         remove_info(f_w, line_number, *(argv + 3));
      }
/*
      while((line_number = search_name(f_w, *(argv + 2))) >= 0)
      {
         remove_info(f_w, line_number, *(argv + 3));
      }
*/
   }
   else if(string_compare(*(argv + 1), "-s") >= 0 && argc == 3)
   {
      if((line_number = search_name(f_w, *(argv + 2))) < 0)
      {
         printf("Not found.\n");
      }
      else
      {
         read_name(f_w, line_number);
      }
   }
   else if(string_compare(*(argv + 1), "-v") >= 0)
   {
      read_all(f_w);
   }
   else
   {
      fprintf(stderr, "%s", program_info);
   }
   return 0;
}

int add_info(char *first_name, char *last_name, char *home_number, char *mobile_number, FILE *f_w)
{
   printf("First name: ");
   str_input(first_name, f_w);
   printf("Last name: ");
   str_input(last_name, f_w);
   printf("Home number: ");
   str_input(home_number, f_w);
   printf("Mobile number: ");
   str_input(mobile_number, f_w);
}

int str_input(char *str, FILE *f_w)
{
   int i = 0;
   f_w = fopen(FILE_PATH, "a");
   while((*(str + i) = getch()) != 13 && i < BUFFER_SIZE)
   {
      printf("%c", *(str + i));
      fputc(*(str + i++), f_w);
   }
   printf("\n");
   fputc('\n', f_w);
   *(str + i) = '\0'; /* all the strings first_name, last_name, home_number, mobile_number could be removed with some small changes to the code. they
                         were added to make it easy to add function later on without haveing to enter the info more then once. */
   fclose(f_w);
   return i;
}

int read_all(FILE *f_w)
{
   if((f_w = fopen(FILE_PATH, "r")) == NULL)
   {
      fprintf(stderr, "File does not exist: %s", FILE_PATH);
      exit(1);
   }
   char c;
   while((c = fgetc(f_w)) != EOF)
   {
      printf("%c", c);
   }
   fclose(f_w);
   return 0;
}

int search_name(FILE *f_w, char *str_search)
{
   if((f_w = fopen(FILE_PATH, "r")) == NULL)
   {
      fprintf(stderr, "File does not exist: %s", FILE_PATH);
      exit(1);
   }
   char c, str[BUFFER_SIZE];
   int i, line_number = 0;
   for(;; i = 0)
   {
      while((c = fgetc(f_w)) != '\n' && c != EOF)
      {
         *(str + i++) = c;
      }
      *(str + i) = '\0';
      if(string_compare(str, str_search) >= 0)
      {
         fclose(f_w);
         return line_number;
      }
      line_number++;
      if(c == EOF)
      {
         break;
      }
   }
   fclose(f_w);
   return -1;
}

int remove_info(FILE *f_w, int line_number, char *del_chk)
{
   if((f_w = fopen(FILE_PATH, "r")) == NULL)
   {
      fprintf(stderr, "File does not exist: %s", FILE_PATH);
      exit(1);
   }
   FILE *f_bak = fopen(BACKUP_DIR, "w");
   char c;
   while((c = fgetc(f_w)) != EOF)
   {
      fputc(c, f_bak);
   }
   fclose(f_w), fclose(f_bak);
   f_w = fopen(FILE_PATH, "w");
   if((f_bak = fopen(BACKUP_DIR, "r")) == NULL)
   {
      fprintf(stderr, "File does not exist: %s", BACKUP_DIR);
      exit(1);
   }
   int row = 0;
   while((c = fgetc(f_bak)) != EOF)
   {
      if((row / 4) == (line_number / 4))
      {
         ;
      }
      else
      {
         fputc(c, f_w);
      }
      if(c == '\n')
      {
         row++;
      }
   }
   fclose(f_w), fclose(f_bak);
   if(string_compare(del_chk, "n") >= 0 || string_compare(del_chk, "N") >= 0)
   {
      remove(BACKUP_DIR);
   }
   return 0;
}

int read_name(FILE *f_w, int line_number)
{
   if((f_w = fopen(FILE_PATH, "r")) == NULL)
   {
      fprintf(stderr, "File does not exist: %s", FILE_PATH);
      exit(1);
   }
   char c;
   int row = 0;
   while((c = fgetc(f_w)) != EOF)
   {
      if((row / 4) == (line_number / 4))
      {
         printf("%c", c);
      }
      if(c == '\n')
      {
         row++;
      }
   }
   fclose(f_w);
   return 0;
}

int string_compare(char *str_01, char *str_02)
{
   int i, j;
   if((j = string_length(str_01)) != string_length(str_02))
   {
      return -1;
   }
   for(i = 0; i < j; i++)
   {
      if(*(str_01 + i) != *(str_02 + i))
      {
         return -1;
      }
   }
   return i;
}

int string_length(char *str)
{
   int i = 0;
   while(*(str + i++) != '\0')
   {
      ;
   }
   return i;
}

if you need any help with this or some other programs in C, pm me.

cheers /dw0rek