C language implements simple electronic address book of 2

  • 2020-09-28 09:05:31
  • OfStack

This paper shares the concrete code of C language to realize simple electronic address book for your reference. The specific content is as follows

After learning system call and standard IO in these two days, some improvements can be made to the previous address book to save the data to a file (I will not send the figure here).

Principle: Every time the program is started, the stored address book information is read from the default file in read-only form, and then imported into the structure. Every time the exit is performed, the default file is opened with update mode, and the information saved in the file is cleared, then the data of the structure is saved in the file, and then the program exits.

In addition, during the file writing and reading, the total number of data to be written (read) to save, let the program know how much data to write (read), then save the number of bytes of each data (the program will save according to the number of bytes of each data), and finally save the data.

Compared with the previous version, only the main function has been changed to include the steps of reading and writing data, and the structure has been changed from one to two, separating Pointers from the original structure to facilitate the import and export of data from the file. Here's the code (so you don't have to go backwards, I revised all the previous code) :

The only modification to the header file head. h is the structure


#ifndef HEAD_H_
#define HEAD_H_

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>       // sleep Function header file 
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#define uint unsigned int
#define OK      0
#define ERROR     -1
#define MALLOC_ERROR -2
#define N       20 


typedef int ElementType;
typedef struct data
{
  ElementType ID;       // ID No. 
  char Name [N];       //  The name 
  char Mobile_Phone [N];   //  Mobile phone number 
  char Home_Address [N];   //  Home address 
  char Company_Tell [N];   //  The phone company 

}Data;
typedef struct _Node
{
  Data data;
  struct _Node* next;     //  Node pointer 
}Node;

typedef Node* PNode;      //  Rename node pointer type 

// Display operation interface 
int Interface_Display ();

// Add friend info  ( The tail interpolation )
int Add_Friend (PNode head, ElementType num);

// Display all friends information 
int Friend_Information (PNode head);

// Looking for friends 
int Search_Friend (PNode head, char* Name);

// Remove buddy 
void Delete_Friend (PNode head, char* Name);

#endif

The source head. c section on the structure has to be modified


#include "head.h"

// Display operation interface 
int Interface_Display ()
{
  system ("clear");
  printf ("\t*****************************************\n");
  printf ("\t~      Welcome to the address book         ~\n");
  printf ("\t~                    ~\n");
  printf ("\t~   1 >>>>>>>>  Add friend info      ~\n");
  printf ("\t~   2 >>>>>>>>  List of friends      ~\n");
  printf ("\t~   3 >>>>>>>>  Search for friends        ~\n");
  printf ("\t~   4 >>>>>>>>  Remove buddy        ~\n");
  printf ("\t~   5 >>>>>>>>  exit          ~\n");
  printf ("\t~                    ~\n");
  printf ("\t~                    ~\n");
  printf ("\t~             The author: believe ~\n");
  printf ("\t*****************************************\n");
  printf ("                      \n");
  printf ("                      \n");
  printf ("\t Please enter the corresponding number to select the corresponding function: ");
}

// Add friend info  ( The tail interpolation )
int Add_Friend (PNode head, ElementType num)
{
  if (NULL == head)
  {
    return ERROR;
  }

  // create 1 A new node 
  PNode p = (PNode) malloc(sizeof(Node)/sizeof(char));
  if (NULL == p)
  {
    return MALLOC_ERROR;
  }

  // Assign new data to the new node 
  system("clear");  
  printf ("\t************* Add buddy ***************\n");

  p->data.ID = num;
  printf ("\t Friend's ID To: %d\n", p->data.ID);
  printf ("\n");

  printf ("\t Please enter your friend's name: ");
  scanf ("%s", p->data.Name);
  printf ("\n");

  printf ("\t Please enter your friend's mobile phone number: ");
  scanf ("%s", p->data.Mobile_Phone);
  printf ("\n");

  printf ("\t Please enter your friend's home address: ");
  scanf ("%s", p->data.Home_Address);
  printf ("\n");

  printf ("\t Please enter your friend's company phone number: ");
  scanf ("%s", p->data.Company_Tell);
  printf ("\n");

  p->next = NULL;

  // To find the last 1 A node 
  PNode Ptmp;         // Gives the header address to a temporary pointer Ptmp
  Ptmp = head;
  while (Ptmp->next)
  {
    Ptmp = Ptmp->next;
  }
  Ptmp->next = p;

  return OK;

}

// Display all friends information 
int Friend_Information (PNode head)
{
  if (NULL == head)
  {
    return ERROR;
  }

  PNode p = head->next;

  printf ("\tID\t The name \t\t Mobile phone no. \t\t address \t\t\t The phone company \n");

  while (p)
  {
    printf ("\t%d\t%s\t\t%s\t\t%s\t\t\t%s\n", p->data.ID, p->data.Name,p->data.Mobile_Phone, p->data.Home_Address, p->data.Company_Tell);
    p = p->next;
  }
  putchar('\n');

  return OK;
}

// Find friends by name 
int Search_Friend (PNode head, char* Name)     
{
  PNode p = head;
  PNode q = NULL;

  if ((NULL != p) && NULL != (p->next))
  {
    while (p->next) 
    {
      q = p->next;
      if ((NULL != q) && 0 == (strcmp(q->data.Name, Name)))
      {
        printf ("\t Friend information : \n\tID:%d\n\t The name : %s\n\t Mobile phone number : %s\n\t Home Address: %s\n\t The phone company : %s\n", q->data.ID, q->data.Name, q->data.Mobile_Phone, q->data.Home_Address, q->data.Company_Tell);
      }
      else
      {
        printf ("\t Sorry, your address book does not have this friend! \n");
      }
      p = p->next;
    }
  }

  /*  On the other 1 Kind of practice 
  if (NULL == head)
  {
    return ERROR;
  }

  PNode p;
  int flag = 1;
  for (p = head->next; p != NULL; p = p->next)
  {
    if (0 == strcmp(p->data.Name, Name))
    {
      flag = 0;
      printf ("\t Friend information: \n\tID: %d\n\t The name : %s\n\t Mobile phone number : %s\n\t Home address : %s\n\t The phone company : %s\n", p->data.ID, p->data.Name, p->data.Mobile_Phone, p->data.Home_Address, p->data.Company_Tell);
    }
  }
  fi (flag)
  {
    printf ("\t Sorry, your address book does not have this friend! \n");
  }

  putchar('\n');
  */

  return OK;
}

// Remove buddy 
void Delete_Friend (PNode head, char* Name)
{
  PNode p = head;
  PNode q = NULL;

  while (NULL != p && NULL != (p->next))
  {
    q = p->next;
    if (NULL != q && 0 == strcmp(q->data.Name, Name))
    {
      p->next = q->next;
      free(q);

      int j;

      printf ("\t deleting \n");
      printf ("\t Please wait for a while ");
      fflush (stdout);      // Force flush cache, output display 
      for (j = 0; j < 2; j++)
      {
        sleep (1);       //linux use sleep , the parameter is seconds 
        printf (".");
        fflush(stdout);     // Force flush cache, output display 
      }
      printf ("\n");
      printf ("\t The friend has been removed successfully! \n");
    }
    else if (NULL == q->next && 0 != strcmp(q->data.Name, Name))
    {
      printf ("\t Your address book does not have this friend! \n");
    }
    p = p->next;
  }
}

The main function main. c, which includes reading and writing of data, is indicated


/*******************************************************************
 Requirements: Production 1 An electronic address book through which friends can be entered ID No., name, ( English ) Hand, 
 Phone number, home address, company phone number. 
 Module: 
   Main interface: Mainly display software functions, A) Add friend info  B) List friend information. ( Contains the sorting 
   function ) C) Search for friends  D) Remove buddy 
  A) User input INSERT After the command, let the user enter friend information. Prompt for success or failure 
  B) User input DISPLAY After the command, the friend information is sorted in ascending order 
  C) User input SEARCH After the command, let the user enter the friend name query to search. If not searched 
   Please be friendly when you arrive. If it is found, the friend information is displayed 
  D) User input DELETE After the command, let the user enter the name of the friend to be deleted, if the same exists 
   Name of multiple friends, then list out all friends of the same name information, let the user through input ID Number deleted 
   Prompt the user for successful deletion. 
**********************************************************************/
#include "head.h"

int main ()
{
  int Function;
  int i = 0;
  char Name[N];
  int cho;

  //  Create a header node and allocate space for it 
  PNode head_node = (PNode) malloc(sizeof(Node)/sizeof(char));
  if (NULL == head_node)
  {
    return MALLOC_ERROR;
  }
  head_node->next = NULL;


/****************************************************************
   Open the file that holds the information and import the data into the central section of the list 
****************************************************************/
  //  Open the file that holds the information read-only. 
  FILE *fp1 = fopen ("student.txt", "r+"); 
  if (NULL == fp1) 
  { 
    printf ("fopen"); 
    return -1; 
  } 

  PNode tmp = head_node; 
  int count; 
  int ret; 

  //  Save the number of read records and determine if you have read to the end of the file. If you have read to the end of the file, 
  //  It returns 1 A non 0  The value of the 
  ret = fread (&count, sizeof(int), 1, fp1); 
  if(ret != 0) 
  { 
    for (i = 0; i < count; i++) 
    {
      //  Create a new node to hold the read data 
      Node *node = (Node*)malloc(sizeof(Node)/sizeof(char));   

      int len;          
      fread (&len, sizeof(int), 1, fp1);   //  Read data length 
      fread (&(node->data), len, 1, fp1);   //  Read the data  

      node->next = NULL;   
      while (tmp->next)            //  Backward traversal 
      { 
        tmp = tmp->next; 
      } 
      tmp->next = node;            //  Import the node into the list  
    } 
  } 

  if (ret == 0 && !feof(fp1))           //  Read failure 
  { 
    perror ("fread"); 
    return -1; 
  } 
  fclose (fp1);                  //  Close the file you just opened 
/****************************************************************
   End of file import list, close file 
****************************************************************/  

  i = 1;               // i Initialization ( i both ID Number) 
  while (1)
  {
    Interface_Display ();      //  The main interface 
    scanf ("%d", &Function);

    switch (Function)        //  Feature selection 
    {
      case 1:           //  Add buddy 
      {
        Function = 0;
        Add_Friend (head_node, i++);
        int j;

        printf ("\t Being added \n");
        printf ("\t Please wait for a while ");
        fflush (stdout);    //  Force flush cache, output display 
        for (j = 0; j < 2; j++)
        {
          sleep (1);     // Linux  use sleep , the parameter is seconds 
          printf (".");
          fflush (stdout);  //  Force flush cache, output display 
        }
        printf ("\n");
        printf ("\t Added successfully! \n");
        printf ("\t Return to the main menu please enter 1 : ");
        scanf ("%d", &cho);
        if (1 == cho)
        {
          break;
        }
        else
        {
          printf ("\t I'm sorry! Your input is incorrect! Please re-enter: ");
          scanf ("%d", &cho);
          break;
        }
        break;
      }      
      case 2:         //  Display friends' information 
      {
        system ("clear");
        printf ("\t*********** Friend information ******************\n");
        printf ("\n");

        Friend_Information (head_node);
        Function = 0;
        printf ("\t Return to the main menu please enter 1 : ");
        scanf ("%d", &cho);
        if (1 == cho)
        {
          break;
        }
        else
        {
          printf ("\t I'm sorry! Your input is incorrect! Please re-enter: ");
          scanf ("%d", &cho);
          break;
        }
        break;
      }
      case 3:         //  Looking for friends 
      {
        system ("clear");
        printf ("\t************* Looking for friends *************\n");
        printf ("\t Please enter the name of the friend you are looking for :");
        scanf ("%s", Name);
        printf ("\n");

        int j;     
        printf ("\t Are looking for \n");
        printf ("\t Please wait for a while ");
        fflush (stdout);    //  Force flush cache, output display 
        for (j = 0; j < 2; j++)
        {
          sleep (1);     // Linux  use sleep , the parameter is seconds 
          printf (".");
          fflush (stdout);  //  Force flush cache, output display 
        }
        printf ("\n");
        Search_Friend (head_node, Name);
        printf ("\t Return to the main menu please enter 1 : ");
        scanf ("%d", &cho);
        if (1 == cho)
        {
          break;
        }
        else
        {
          printf ("\t I'm sorry! Your input is incorrect! Please re-enter: ");
          scanf ("%d", &cho);
          break;
        }
        break;
      }
      case 4:           // Remove buddy 
      {
        system ("clear");
        printf ("\t************* Remove buddy *************\n");
        printf ("\t Please enter the name of the friend you want to remove :");
        scanf ("%s", Name);
        printf ("\n");
        Delete_Friend (head_node, Name);
        printf ("\t Return to the main menu please enter 1 : ");
        scanf ("%d", &cho);
        if (1 == cho)
        {
          break;
        }
        else
        {
          printf ("\t I'm sorry! Your input is incorrect! Please re-enter: ");
          scanf ("%d", &cho);
          break;
        }
        break;
      }  
      case 5:           // Exit address book 
      {

/****************************************************************
         Before exiting the program, import the data from the linked list into a file 
****************************************************************/
        //  Open the file that holds the information in an update mode (empty the file when opened) 
        FILE *fp2 = fopen ("student.txt", "wb+"); 
        if(NULL == fp2) 
        { 
          printf ("fopen"); 
          return -1; 
        } 

        tmp = head_node->next;     // tmp For the first 1 A node 
        count = 0;           //  Used to store the list length 
        while(tmp)           //  Find the length of the list 
        { 
          count++; 
          tmp = tmp->next; 
        }

        //  The number of data to write 
        fwrite(&count, sizeof(int), 1, fp2); 
        tmp = head_node;        // tmp Initialize the 
        while (tmp->next) 
        { 
          Node* p = tmp->next; 
          tmp->next = p->next; 

          //  The length of the data being written          
          int len = sizeof(p->data); 
          fwrite (&len, sizeof(int), 1, fp2); 

          // Write data  
          fwrite (&(p->data), sizeof(Data), 1, fp2); 

          free (p);          
        } 
        fclose (fp2); 
/****************************************************************
         Data saving finished, about to exit the program 
****************************************************************/

        Function = 0;
        system ("clear");
        exit (0);
      }
      default:          // Input is wrong 
      {
        Function = 0;
        printf ("\t I'm sorry! Your input is incorrect! Please re-enter: ");
        scanf ("%d", &Function);
        break;
      }      
    }    
  }  

  return 0;
}

Related articles: