当前位置:网站首页>Realize a binary read-write address book
Realize a binary read-write address book
2022-07-06 04:57:00 【A little bit】
Realize a binary read-write address book
results
- A binary read-write address book , After each procedure , The entered information will be saved to the folder where the current project is located ( Of course, the path can be changed )
- The written address book is in binary form , So if it is not read in binary , I can't understand the contents
- Integrate knowledge points : Structure , Dynamic memory allocation , Callback function , Classification of methods , The pointer , Document reading and writing, etc .
Implementation steps
- The header file defines some identifier constants and header files , Of course, the types commonly used in programs can also be written here , For example, the personal information in the following code ( Structure ) And contacts ( Nested structure ), Of course, the most important thing is the function declaration
- Define two source files respectively , It is used for the specific implementation of each function and the final function test
- In fact, we can first implement the static version of the address book ( Dynamic memory development is not involved ), Then optimize it into a dynamic version ( First of all : There is no longer an upper limit on the number of contacts , Secondly, space can be fully utilized ), Finally, the reading and writing of the composition makes the contact information persistent .
Code
//contact.h
#pragma once
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define NAME_MAX 10
#define SEX_MAX 5
#define TEL_MAX 15
#define ADDR_MAX 30
#define DEFAULT_SZ 3
#define INCREASED_SZ 2
// Personal information
struct PeopInfo
{
char name[NAME_MAX];
int age;
char sex[SEX_MAX];
char tel[TEL_MAX];
char addr[ADDR_MAX];
};
// The whole address book
struct contact
{
struct PeopInfo* data;
int sz;// Record the number of valid data
int capacity;// Record the maximum capacity of the current address book
};
// Initialize address book
void initContact(struct contact* pc);
// Add a Contact
void AddContact(struct contact* pc);
// Print address book
void ShowContact(struct contact* pc);
// Delete Contact ( By name )
void DelContact(struct contact* pc);
// Find contacts ( By name ), And print
void SearchContact(struct contact* pc);
// Modify contact information
void ModifyContact(struct contact* pc);
// Destroy the address book
void DestoryContact(struct contact* pc);
// Sort by age
void SortContact(struct contact* pc);
// Save the address book information to the file
void SaveContact(struct contact* pc);
// Load address book information
void LoadContact(struct contact* pc);
// Check the capacity
void CheckCapacity(struct contact* pc);
//contact.c
#include "contact.h"
// Check the capacity
void CheckCapacity(struct contact* pc)
{
if (pc->sz == pc->capacity)
{
// The data is full , Increase capacity
struct PeopInfo* tmp = (struct PeopInfo*)realloc(pc->data, (2 + pc->capacity) * sizeof(struct PeopInfo));// Expand two
if (tmp != NULL)
{
pc->data = tmp;
// Successful expansion , And the capacity increased each time is defaulted to 2 individual
pc->capacity += 2;
//printf(" Successful expansion !\n");
}
else
{
perror(" Address book capacity increase failed ");
exit(1);
}
}
}
// Load address book information
void LoadContact(struct contact* pc)
{
FILE* pf = fopen("contact.txt", "rb");
if (pf == NULL)
{
perror("LoadContact::fopen");
return;
}
struct PeopInfo tmp = {
0 };
while (fread(&tmp, sizeof(struct PeopInfo), 1, pf))// Read one at a time
{
// If the space is not enough, you need to increase the space
CheckCapacity(pc);
pc->data[pc->sz] = tmp;
pc->sz++;
}
fclose(pf);
pf = NULL;
}
// Initialize address book
void initContact(struct contact* pc)
{
pc->sz = 0;// At first, there was no data
pc->data = (struct PeopInfo*)malloc(DEFAULT_SZ * sizeof(struct PeopInfo));// By default, three spaces are initialized to store information
pc->capacity = DEFAULT_SZ;// That is, the default initialization capacity
// Load the information in the file into the address book
LoadContact(pc);
}
// Find the specified contact by name
int FindByName(struct contact* pc, char* name)
{
int ret = -1;
for (int i = 0; i < pc->sz; i++)
{
if (strcmp(name, pc->data[i].name) == 0)
{
ret = i;
break;
}
}
return ret;
}
// Add a Contact
void AddContact(struct contact* pc)
{
CheckCapacity(pc);
struct PeopInfo tmp = {
0 };
printf(" Please enter a name :");
scanf("%s", tmp.name);
printf(" Please enter age :");
scanf("%d", &(tmp.age));
printf(" Please enter gender :");
scanf("%s", tmp.sex);
printf(" Please input the phone number :");
scanf("%s", tmp.tel);
printf(" Please enter the address :");
scanf("%s", tmp.addr);
pc->data[pc->sz] = tmp;
pc->sz++;
printf(" Contact added successfully !\n");
}
// Print address book
void ShowContact(struct contact* pc)
{
if (pc->sz == 0)
{
printf(" Address book is empty !\n");
return;
}
// When the address book is not empty
printf("%-5s\t%-5s\t%-5s\t%-15s\t\t%-20s\n", " full name ", " Age ", " Gender ", " Telephone ", " Address ");
for (int i = 0; i < pc->sz; i++)
{
printf("%-5s\t%-5d\t%-5s\t%-15s\t\t%-20s\n", pc->data[i].name,
pc->data[i].age,pc->data[i].sex,pc->data[i].tel,pc->data[i].addr);
}
}
// Delete the specified contact
void DelContact(struct contact* pc)
{
char name[NAME_MAX];
printf(" Please enter the contact name to be deleted :");
scanf("%s", name);
int ret = FindByName(pc, name);
if (ret == -1)
{
printf(" Check no one !\n");
return;
}
for (int i = ret; i < pc->sz-1; i++)
{
pc->data[i] = pc->data[i + 1];// The next data overwrites the previous data
}
pc->sz--;
printf(" Delete contact successfully !\n");
}
// Find the specified contact
void SearchContact(struct contact* pc)
{
char name[NAME_MAX];
printf(" Please enter the name of the contact you are looking for :");
scanf("%s", name);
int ret = FindByName(pc, name);
if (ret == -1)
{
printf(" Check no one !\n");
return;
}
printf("%-5s\t%-5s\t%-5s\t%-15s\t\t%-20s\n", " full name ", " Age ", " Gender ", " Telephone ", " Address ");// Print a title
printf("%-5s\t%-5d\t%-5s\t%-15s\t\t%-20s\n", pc->data[ret].name,
pc->data[ret].age, pc->data[ret].sex, pc->data[ret].tel, pc->data[ret].addr);
}
// Modify contact information
void ModifyContact(struct contact* pc)
{
char name[NAME_MAX];
printf(" Please enter the contact name to be modified :");
scanf("%s", name);
int ret = FindByName(pc, name);
if (ret == -1)
{
printf(" Check no one \n");
return;
}
struct PeopInfo tmp = {
0 };
printf(" Please enter a new name :");
scanf("%s", tmp.name);
printf(" Please enter a new age :");
scanf("%d", &(tmp.age));
printf(" Please enter a new gender :");
scanf("%s", tmp.sex);
printf(" Please enter a new phone number :");
scanf("%s", tmp.tel);
printf(" Please enter a new address :");
scanf("%s", tmp.addr);
pc->data[ret] = tmp;
printf(" Successfully modified the specified contact information !\n");
}
// Destroy the address book
void DestoryContact(struct contact* pc)
{
free(pc->data);
pc->data = NULL;
pc->sz = 0;
pc->capacity = 0;
}
// Sort by age
int compare(const void* e1, const void* e2)
{
return ((struct PeopInfo*)e1)->age-((struct PeopInfo*)e2)->age;
}
void SortContact(struct contact* pc)
{
if (pc->sz == 0)
{
printf(" The address book is currently empty !\n");
return;
}
qsort(pc->data, pc->sz, sizeof(struct PeopInfo), compare);
printf(" Rank success by age !\n");
}
// Save address book information
void SaveContact(struct contact* pc)
{
FILE* pf = fopen("contact.txt", "wb");// Binary write
if (pf == NULL)
{
perror("SaveContact::fopen");
return;
}
// File opened successfully
for (int i = 0; i < pc->sz; i++)
{
fwrite(&(pc->data[i]), sizeof(struct PeopInfo), 1, pf);
}
fclose(pf);
pf = NULL;
}
//test.c
#include "contact.h"
void menu()
{
printf("***********************************\n");
printf("******** 1.add 2.del *******\n");
printf("******** 3.search 4.modify *******\n");
printf("******** 5.show 6.sort *******\n");
printf("******** 0.exit *******\n");
printf("***********************************\n");
}
enum Option
{
EXIT,
ADD,
DEL,
SEARCH,
MODIFY,
SHOW,
SORT
};
int main()
{
int input = 0;
struct contact con;// Create an address book
// Initialize address book
initContact(&con);
do
{
menu();
printf(" Please enter your choice :>");
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 EXIT:
// sign out cmd At the window , You need to save the address book information to the file first
SaveContact(&con);
DestoryContact(&con);
printf(" Exit address book successfully !\n");
break;
case SORT:
SortContact(&con);
break;
default:
printf(" Incorrect input , Please reselect :");
break;
}
} while (input);
return 0;
}
Exchange in question comment area
边栏推荐
- Bubble sort
- SQL注入漏洞(MSSQL注入)
- 你需要知道的 TCP 三次握手
- ORM aggregate query and native database operation
- win10电脑系统里的视频不显示缩略图
- 组播和广播的知识点梳理
- RT thread analysis - object container implementation and function
- Codeforces Round #804 (Div. 2)
- C'est un petit résumé de l'étude.
- The video in win10 computer system does not display thumbnails
猜你喜欢
8. Static file
Distributed transaction solution
[FreeRTOS interrupt experiment]
Postman关联
Compilation and connection of shader in games202 webgl (learn from)
L'introduction en bourse de MSK Electronics a pris fin: 800 millions de RMB d'actifs de Henan étaient des actionnaires
图论的扩展
Visio draws Tai Chi
Postman pre script - global variables and environment variables
The ECU of 21 Audi q5l 45tfsi brushes is upgraded to master special adjustment, and the horsepower is safely and stably increased to 305 horsepower
随机推荐
Fuzzy -- basic application method of AFL
Distributed transaction solution
Redis 排查大 key 的4種方法,優化必備
yolov5 tensorrt加速
Set detailed map + interview questions
web工程导入了mysql驱动jar包却无法加载到驱动的问题
ue5 小知识 FreezeRendering 查看视锥内渲染的物体
Selection sort
Redis has four methods for checking big keys, which are necessary for optimization
内核判断i2c地址上是否挂载外设
[lgr-109] Luogu may race II & windy round 6
Biscuits (examination version)
Class inheritance in yyds dry inventory C
Introduction of several RS485 isolated communication schemes
力扣(LeetCode)186. 翻转字符串里的单词 II(2022.07.05)
The video in win10 computer system does not display thumbnails
Programmers' position in the Internet industry | daily anecdotes
Three.js学习-光照和阴影(了解向)
Postman assertion
[Chongqing Guangdong education] engineering fluid mechanics reference materials of southwestjiaotonguniversity