当前位置:网站首页>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
边栏推荐
- Biscuits (examination version)
- [lgr-109] Luogu may race II & windy round 6
- Driver development - hellowdm driver
- Raspberry pie 3.5-inch white screen display connection
- Selection of slow motion function
- EditorUtility.SetDirty在Untiy中的作用以及应用
- TCP three handshakes you need to know
- 麦斯克电子IPO被终止:曾拟募资8亿 河南资产是股东
- GAMES202-WebGL中shader的編譯和連接(了解向)
- Microservice resource address
猜你喜欢
![[Yu Yue education] reference materials of complex variable function and integral transformation of Northwestern Polytechnic University](/img/22/ead74bc121a64910ef6ef374cd029b.png)
[Yu Yue education] reference materials of complex variable function and integral transformation of Northwestern Polytechnic University

ORM aggregate query and native database operation

Crazy God said redis notes

RT thread analysis - object container implementation and function

Orm-f & Q object

What are the advantages of the industry private network over the public network? What specific requirements can be met?

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

二叉树基本知识和例题

Postman Association

Postman manage test cases
随机推荐
Application of Flody
也算是學習中的小總結
Extension of graph theory
Basic knowledge and examples of binary tree
DMA use of stm32
2021 robocom world robot developer competition - undergraduate group (semi-finals)
Postman Association
ORM aggregate query and native database operation
Flink kakfa data read and write to Hudi
Redis has four methods for checking big keys, which are necessary for optimization
Acwing week 58
[数学建模] 微分方程--捕鱼业的持续发展
Building intelligent gray-scale data system from 0 to 1: Taking vivo game center as an example
集合详解之 Map + 面试题
【Try to Hack】john哈希破解工具
Fuzzy -- basic application method of AFL
Why does MySQL need two-phase commit
Idea one key guide package
How does vs change the project type?
Platformio create libopencm3 + FreeRTOS project