当前位置:网站首页>[C language implementation] - dynamic / file / static address book
[C language implementation] - dynamic / file / static address book
2022-07-26 19:20:00 【whispar】

author whispar
special column : C Language from scratch
Lower your posture , Empty cup mentality

Catalog
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 !!

边栏推荐
- 2022年流动式起重机司机考试试题模拟考试平台操作
- Racher deploys kubernetes cluster
- C#获取本地时间/系统时间
- 手机申请公募reits账户安全吗?
- 时空预测4-graph wavenet
- JS刷题计划——数组
- ZbxTable 2.0 重磅发布!6大主要优化功能!
- Vs2019 export import configuration
- C#创建及读取DAT文件案例
- Covos: no need to decode! Semi supervised Vos acceleration using motion vectors and residuals of compressed video bitstreams (CVPR 2022)
猜你喜欢

Reentrantlock learning - lock release process

篇7:exited on DESKTOP-DFF5KIK with error code -1073741511.

MySQL learning notes -2. how to improve the query performance of SQL statements

PMP每日一练 | 考试不迷路-7.26(包含敏捷+多选)

2022年流动式起重机司机考试试题模拟考试平台操作

Introduction to Seata

Mathematical basis of deep learning

【YOLOv5】--详细版训练自己的数据集 保姆级学习日志记录 手把手教程

(ICLR-2022)TADA! Time adaptive convolution for video understanding

ReentrantLock学习之---释放锁过程
随机推荐
[swoole series 3.1] have you been asked about processes, threads, and collaborations during the interview?
Agenda express | list of sub forum agenda on July 27
The inventory of chips in the United States is high, and the shipment of chips in China has increased rapidly and the import of 28.3 billion chips has been greatly reduced. TSMC has a showdown
时空预测5-GAT
多线程学习笔记-1.CAS
JS map usage
Redis学习笔记-2.客户端的使用
洋葱集团携手OceanBase实现分布式升级,全球数据首次实现跨云融合
(ICLR-2022)TADA!用于视频理解的时间自适应卷积
从6月25日考试之后,看新考纲如何复习PMP
PMP practice once a day | don't get lost in the exam -7.26 (including agility + multiple choices)
Is it safe to apply for public REITs account by mobile phone?
Distributed transaction Seata
最后一篇博客
Reentrantlock learning --- basic method
(ICLR-2022)TADA! Time adaptive convolution for video understanding
Complete MySQL database commands
香港高防IP优势及哪些行业适合使用
conda+pytorch环境教程
[postgraduate entrance examination vocabulary training camp] day 13 - reliance, expert, subject, unconscious, photograph, exaggeration, counter act