当前位置:网站首页>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
边栏推荐
- [mathematical modeling] differential equation -- sustainable development of fishing industry
- Uva1592 Database
- Request (request object) and response (response object)
- EditorUtility. The role and application of setdirty in untiy
- Rce code and Command Execution Vulnerability
- Finance online homework
- Lepton 无损压缩原理及性能分析
- Yyds dry goods inventory OSI & tcp/ip
- 项目经理,你会画原型嘛?项目经理需要做产品设计了?
- Distributed transaction solution
猜你喜欢
How to estimate the population with samples? (mean, variance, standard deviation)
11. Intranet penetration and automatic refresh
程序员在互联网行业的地位 | 每日趣闻
MPLS experiment
Class inheritance in yyds dry inventory C
Visio draws Tai Chi
Postman关联
RT thread analysis - object container implementation and function
L'introduction en bourse de MSK Electronics a pris fin: 800 millions de RMB d'actifs de Henan étaient des actionnaires
GAMES202-WebGL中shader的编译和连接(了解向)
随机推荐
优秀PM必须经历这3层蜕变!
Compilation et connexion de shader dans games202 - webgl (comprendre la direction)
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
The web project imported the MySQL driver jar package but failed to load it into the driver
Postman断言
Bubble sort
Uva1592 Database
程序员在互联网行业的地位 | 每日趣闻
Sqlserver query results are not displayed in tabular form. How to modify them
Visio draws Tai Chi
Fuzzy -- basic application method of AFL
Embedded development program framework
ISP learning (2)
Finance online homework
Pagoda configuration mongodb
行业专网对比公网,优势在哪儿?能满足什么特定要求?
Leetcode dynamic planning day 16
[Chongqing Guangdong education] Suzhou University English film and Television Appreciation reference materials
Basic knowledge and examples of binary tree
Platformio create libopencm3 + FreeRTOS project