当前位置:网站首页>[C language implementation] - dynamic / file / static address book

[C language implementation] - dynamic / file / static address book

2022-07-26 19:20:00 whispar

ced485cbb11e458d81a746890b32cf3f.gif

  author  whispar
special column : C Language from scratch

Lower your posture , Empty cup mentality

7abc9c8906564477a6679bb15d368e37.gif

Catalog

One 、 Code display

test.c

contact.c

contact.h

Two 、 Effect display

Implementation of basic functions of static version

Implementation of dynamic version expansion function  

The local function of saving the file version


One 、 Code display

test.c

Using enumerated types , Make the code of the menu part more readable , Easy to understand

#define _CRT_SECURE_NO_WARNINGS
​
#include"contact.h"
enum Option
{
    EXIT,
    ADD,
    DEL,
    SEARCH,
    MODIFY,
    SHOW,
    SORT
};
void menu() {
    printf("*******\ 1.add     2.del    /*******\n");
    printf("*******\ 3.search  4.modify /*******\n");
    printf("*******\ 5.show    6.sort   /*******\n");
}
int main(){
    int input = 0;
    Contact con; // Mail list 
    // Structural parameters 
    InitContact(&con); // Structural parameters 
    do
    {
        menu();
        printf(" Please select :> ");
        scanf("%d", &input);
        switch (input)
        {
        case ADD:
            AddContact(&con);
            break;
        case DEL:
            DelContact(&con);
            break;
        case SEARCH:
            SearchContact(&con);
            break;
        case MODIFY:
            ModifyContact(&con);
            break;
        case SHOW:
            ShowContact(&con);
            break;
        case SORT:
            SortContact(&con);
            break;
        case EXIT:
            SaveContact(&con);
            DestroyContact(&con);
            printf(" Exit address book \n");
            break;
        default:
            printf(" Wrong choice \n");
            break;
        }
    } while (input);
​
    return 0;
}
​

contact.c

stay contact.c The static version in cannot meet our needs , So we use in dynamic versions realloc Function can be used to dynamically open up the memory size , We can encapsulate a function to determine whether the capacity is sufficient , If not enough, expand the capacity .

stay contact.c The version of the file in can store the created data locally , When the program exits , The data still exists , Using files, we can store data directly on the hard disk of the computer , Data persistence is achieved .
 

#define _CRT_SECURE_NO_WARNINGS 1
​
#include "contact.h"
​
// Static version 
//void InitContact(Contact* pc)
//{
//  assert(pc);
//  pc->count = 0;
//  memset(pc->data, 0, sizeof(pc->data));
//}
​

void CheckCapacity(Contact* pc)
{
    if (pc->count == pc->capacity)
    {
        PeoInfo* ptr = (PeoInfo*)realloc(pc->data, (pc->capacity + INC_SZ) * sizeof(PeoInfo));
        if (ptr == NULL)
        {
            printf("AddContact::%s\n", strerror(errno));
            return;
        }
        else
        {
            pc->data = ptr;
            pc->capacity += INC_SZ;
            printf(" Successful expansion \n");
        }
    }
}
​
void LoadContact(Contact* pc)
{
    FILE* pfRead = fopen("contact.txt", "rb");
    if (pfRead == NULL)
    {
        perror("LoadContact");
        return;
    }
    PeoInfo tmp = { 0 };
​
    while (fread(&tmp, sizeof(PeoInfo), 1, pfRead) == 1)
    {
        CheckCapacity(pc);
​
        pc->data[pc->count] = tmp;
        pc->count++;
    }
​
    fclose(pfRead);
    pfRead = NULL;
}
​
// Dynamic version 
int InitContact(Contact* pc)
{
    assert(pc);
    pc->count = 0;
    pc->data = (PeoInfo*)calloc(DEFAULT_SZ, sizeof(PeoInfo));
    if (pc->data == NULL)
    {
        printf("InitContact::%s\n", strerror(errno));
        return 1;
    }
    pc->capacity = DEFAULT_SZ;
    // Load the information of the file into the address book 
    LoadContact(pc);
    return 0;
}
​
void DestroyContact(Contact* pc)
{
    assert(pc);
    free(pc->data);
    pc->data = NULL;
}
​
// Static version 
//void AddContact(Contact* pc)
//{
//  assert(pc);
//  if (pc->count == MAX)
//  {
//      printf(" The address book is full , Unable to add \n");
//      return;
//  }
//  //
//  printf(" Please enter a name :>");
//  scanf("%s", pc->data[pc->count].name);
//  printf(" Please enter age :>");
//  scanf("%d", &(pc->data[pc->count].age));
//  printf(" Please enter gender :>");
//  scanf("%s", pc->data[pc->count].sex);
//  printf(" Please input the phone number :>");
//  scanf("%s", pc->data[pc->count].tele);
//  printf(" Please enter the address :>");
//  scanf("%s", pc->data[pc->count].addr);
//
//  pc->count++;
//  printf(" Increase success \n");
//}
​
​
​
// Dynamic version 
void AddContact(Contact* pc)
{
    assert(pc);
    // increase capacity 
    CheckCapacity(pc);
    //
    printf(" Please enter a name :>");
    scanf("%s", pc->data[pc->count].name);
    printf(" Please enter age :>");
    scanf("%d", &(pc->data[pc->count].age));
    printf(" Please enter gender :>");
    scanf("%s", pc->data[pc->count].sex);
    printf(" Please input the phone number :>");
    scanf("%s", pc->data[pc->count].tele);
    printf(" Please enter the address :>");
    scanf("%s", pc->data[pc->count].addr);
​
    pc->count++;
    printf(" Increase success \n");
}
​
void ShowContact(const Contact* pc)
{
    assert(pc);
    int i = 0;
    printf("%-20s\t%-5s\t%-5s\t%-12s\t%-30s\n", " name ", " Age ", " Gender ", " Telephone ", " Address ");
    for (i = 0; i < pc->count; i++)
    {
        printf("%-20s\t%-5d\t%-5s\t%-12s\t%-30s\n", pc->data[i].name,
            pc->data[i].age,
            pc->data[i].sex,
            pc->data[i].tele,
            pc->data[i].addr);
    }
}
​
static int FindByName(Contact* pc, char name[])
{
    assert(pc);
    int i = 0;
    for (i = 0; i < pc->count; i++)
    {
        if (0 == strcmp(pc->data[i].name, name))
        {
            return i;
        }
    }
​
    return -1;
}
​
void DelContact(Contact* pc)
{
    char name[MAX_NAME] = { 0 };
    assert(pc);
    int i = 0;
    if (pc->count == 0)
    {
        printf(" Address book is empty , No information can be deleted \n");
        return;
    }
    printf(" Please enter the name of the person you want to delete :>");
    scanf("%s", name);
    // Delete 
    //1.  lookup 
    int pos = FindByName(pc, name);
    if (pos == -1)
    {
        printf(" The person to delete does not exist \n");
        return;
    }
    //2.  Delete 
    for (i = pos; i < pc->count - 1; i++)
    {
        pc->data[i] = pc->data[i + 1];
    }
    pc->count--;
​
    printf(" Delete successful \n");
}
​
void SearchContact(Contact* pc)
{
    assert(pc);
    char name[MAX_NAME] = { 0 };
    printf(" Please enter the name of the person you want to search for :>");
    scanf("%s", name);
    //1.  lookup 
    int pos = FindByName(pc, name);
    if (pos == -1)
    {
        printf(" The person you're looking for doesn't exist \n");
        return;
    }
    //2.  Print 
    printf("%-20s\t%-5s\t%-5s\t%-12s\t%-30s\n", " name ", " Age ", " Gender ", " Telephone ", " Address ");
    printf("%-20s\t%-5d\t%-5s\t%-12s\t%-30s\n", pc->data[pos].name,
        pc->data[pos].age,
        pc->data[pos].sex,
        pc->data[pos].tele,
        pc->data[pos].addr);
}
​
​
void ModifyContact(Contact* pc)
{
    assert(pc);
    char name[MAX_NAME] = { 0 };
    printf(" Please enter the name of the person you want to modify :>");
    scanf("%s", name);
    //1.  lookup 
    int pos = FindByName(pc, name);
    if (pos == -1)
    {
        printf(" The person to modify does not exist \n");
        return;
    }
    printf(" The information of the person to be modified has been found , Next, start to modify \n");
    //2.  modify 
    printf(" Please enter a name :>");
    scanf("%s", pc->data[pos].name);
    printf(" Please enter age :>");
    scanf("%d", &(pc->data[pos].age));
    printf(" Please enter gender :>");
    scanf("%s", pc->data[pos].sex);
    printf(" Please input the phone number :>");
    scanf("%s", pc->data[pos].tele);
    printf(" Please enter the address :>");
    scanf("%s", pc->data[pos].addr);
​
    printf(" Modification successful \n");
}
​
​
int cmp_peo_by_name(const void* e1, const void* e2)
{
    return strcmp(((PeoInfo*)e1)->name, ((PeoInfo*)e2)->name);
}
​
// Sort by name 
void SortContact(Contact* pc)
{
    assert(pc);
    qsort(pc->data, pc->count, sizeof(PeoInfo), cmp_peo_by_name);
    printf(" Sort success \n");
}
​
void SaveContact(const Contact* pc)
{
    assert(pc);
    FILE* pfWrite = fopen("contact.txt", "wb");
    if (pfWrite == NULL)
    {
        perror("SaveContact");
        return;
    }
    // Writing documents - Binary form 
    int i = 0;
    for (i = 0; i < pc->count; i++)
    {
        fwrite(pc->data + i, sizeof(PeoInfo), 1, pfWrite);
    }
​
    fclose(pfWrite);
    pfWrite = NULL;
}
​
​

contact.h

#pragma once
​
#include <string.h>
#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
​
#define DEFAULT_SZ 3
#define INC_SZ 2
​
#define MAX 100
#define MAX_NAME 20
#define MAX_SEX 10
#define MAX_TELE 12
#define MAX_ADDR 30
​
// Declaration of type 
// 
// Human information 
typedef struct PeoInfo
{
    char name[MAX_NAME];
    int age;
    char sex[MAX_SEX];
    char tele[MAX_TELE];
    char addr[MAX_ADDR];
} PeoInfo;
​
​
// Mail list 
​
// Static version 
//typedef struct Contact
//{
//  PeoInfo data[MAX];// Depositor's information 
//  int count;// Record the actual number of people in the current address book 
//}Contact;
​
// Dynamic version 
typedef struct Contact
{
    PeoInfo* data;// Depositor's information 
    int count;// Record the actual number of people in the current address book 
    int capacity;// Current address book capacity 
}Contact;
​
​
// Initialize address book 
int InitContact(Contact* pc);
​
// Destroy the address book 
void DestroyContact(Contact* pc);
​
// Add contacts and contacts 
void AddContact(Contact* pc);
​
// Print the information in the communication 
void ShowContact(const Contact* pc);
​
// Delete designated contact 
void DelContact(Contact* pc);
​
// Find the designated contact 
void SearchContact(Contact* pc);
​
// Modify the designated contact 
void ModifyContact(Contact* pc);
​
// Sort the contents in the address book 
// Sort by name 
// Sort by age 
//...
void SortContact(Contact* pc);
​
// Save the information of the address book to a file 
void SaveContact(const Contact* pc);
​
// Load the information of the file into the address book 
void LoadContact(Contact* pc);
​

Two 、 Effect display

Implementation of basic functions of static version

Implementation of dynamic version expansion function  

The local function of saving the file version

    If it helps you , Please do more thumb up 、 Collection 、 Comment on 、 Focus on supporting !!             

ced485cbb11e458d81a746890b32cf3f.gif

原网站

版权声明
本文为[whispar]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/207/202207261809008252.html