当前位置:网站首页>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
边栏推荐
- Ue5 small knowledge freezerendering view rendered objects in the cone
- Unity screen coordinates ugui coordinates world coordinates conversion between three coordinate systems
- Selection of slow motion function
- Visio draw fan
- Programmers' position in the Internet industry | daily anecdotes
- 2021RoboCom机器人开发者大赛(初赛)
- Extension of graph theory
- 關於Unity Inspector上的一些常用技巧,一般用於編輯器擴展或者其他
- Digital children < daily question> (Digital DP)
- Platformio create libopencm3 + FreeRTOS project
猜你喜欢
ue5 小知识点 开启lumen的设置
IPv6 comprehensive experiment
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
What are the advantages of the industry private network over the public network? What specific requirements can be met?
[05-1, 05-02, 05-03] network protocol
Postman关联
Flink kakfa data read and write to Hudi
Digital children < daily question> (Digital DP)
Ue5 small knowledge points to enable the setting of lumen
Visio draws Tai Chi
随机推荐
ISP learning (2)
web工程导入了mysql驱动jar包却无法加载到驱动的问题
麦斯克电子IPO被终止:曾拟募资8亿 河南资产是股东
Postman test report
Postman assertion
Microblogging hot search stock selection strategy
Postman manage test cases
EditorUtility. The role and application of setdirty in untiy
C'est un petit résumé de l'étude.
集合详解之 Map + 面试题
Selection sort
[05-1, 05-02, 05-03] network protocol
Redis 排查大 key 的4種方法,優化必備
The video in win10 computer system does not display thumbnails
Postman断言
Bill Gates posted his 18-year-old resume and expected an annual salary of $12000 48 years ago
你需要知道的 TCP 三次握手
[NOIP2009 普及组] 分数线划定
Acwing week 58
Basic knowledge and examples of binary tree