当前位置:网站首页>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
边栏推荐
- [Chongqing Guangdong education] Suzhou University English film and Television Appreciation reference materials
- Postman manage test cases
- [lgr-109] Luogu may race II & windy round 6
- 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
- 关于Unity Inspector上的一些常用技巧,一般用于编辑器扩展或者其他
- 行业专网对比公网,优势在哪儿?能满足什么特定要求?
- [Yu Yue education] reference materials of complex variable function and integral transformation of Northwestern Polytechnic University
- 也算是学习中的小总结
- Bill Gates posted his 18-year-old resume and expected an annual salary of $12000 48 years ago
- web工程导入了mysql驱动jar包却无法加载到驱动的问题
猜你喜欢
![[数学建模] 微分方程--捕鱼业的持续发展](/img/7c/2ab6f2a34bc2c97318537ec8e0b0c5.png)
[数学建模] 微分方程--捕鱼业的持续发展

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

RT thread analysis - object container implementation and function

Visio draws Tai Chi

RTP gb28181 document testing tool

Crazy God said redis notes

Zynq learning notes (3) - partial reconfiguration

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

Basic knowledge and examples of binary tree
随机推荐
L'introduction en bourse de MSK Electronics a pris fin: 800 millions de RMB d'actifs de Henan étaient des actionnaires
SQL注入漏洞(MSSQL注入)
Project manager, can you draw prototypes? Does the project manager need to do product design?
Raspberry pie 3.5-inch white screen display connection
【Try to Hack】john哈希破解工具
Embedded development program framework
TCP three handshakes you need to know
GAMES202-WebGL中shader的编译和连接(了解向)
Rce code and Command Execution Vulnerability
Redis has four methods for checking big keys, which are necessary for optimization
Lepton 无损压缩原理及性能分析
Bill Gates posted his 18-year-old resume and expected an annual salary of $12000 48 years ago
Building intelligent gray-scale data system from 0 to 1: Taking vivo game center as an example
Luogu deep foundation part 1 Introduction to language Chapter 2 sequential structure programming
Postman断言
Use sentinel to interface locally
The IPO of mesk Electronics was terminated: Henan assets, which was once intended to raise 800 million yuan, was a shareholder
Summary of three log knowledge points of MySQL
Excellent PM must experience these three levels of transformation!
也算是学习中的小总结