当前位置:网站首页>Implementation of address book (file version)
Implementation of address book (file version)
2022-07-02 11:49:00 【Less debug every day】
Indexes
Design requirements
Everyone's information doesn't just have numbers , We can also design gender and age , So the subject we choose is a structure
struct info
{
char name[MAX_NAME];
char sex[MAX_SEX];
char phone[MAX_PHONENUMBER];
char address[MAX_ADDRESS];
int age;
};
The dynamic version is better when designing the address book , So we add a structure to the original structure
struct contact
{
struct info* data;
int sz;
int capacity;
};
among capacity Indicates the capacity size ,sz Indicates the current number of contacts in the address book , When capacity==sz Capacity expansion is required at this time
Test.c
First, we need to write an enumeration constant
enum choice
{
EXIT,// sign out
ADD,// Add a Contact
DEL,// Delete Contact
SEARCH,// Find contacts
MODIFY,// Modify address book
SHOW,// Show the address book
CLEAR,// Clear address book
SORT// Sort the address book
};
If there is no assignment, it defaults from 0 Start , In this way, even if others only see our document, they can immediately understand the meaning of the numerical options .
Then there are some routine operations similar to the previous ones
void menu()
{
printf("****************************************************************************\n");
printf("***********************0. Exit address book *******1. Add a Contact ***********************\n");
printf("***********************2. Delete Contact *******3. Find contacts ***********************\n");
printf("***********************4. Modify contact ********5. Show the address book **********************\n");
printf("***********************6. Format address book ******7, Sort contacts *******************\n");
printf("******************************************************************************\n");
}
int main()
{
struct contact con;
// Initialize address book
Init_Contact(&con);
int input = 0;
int size = 0;// Record how many people there are currently
do
{
menu();
printf(" Please select ->\n");
scanf("%d", &input);
switch (input)
{
case ADD:
Add_Contact(&con);
break;
case DEL:
Del_Contact(&con);
break;
case SEARCH:
Search_Contact(&con);
break;
case MODIFY:
Modify_Contact(&con);
break;
case SHOW:
system("cls");
Show_Contact(&con);
break;
case CLEAR:
Clear_Contact(&con);
break;
case SORT:
Sort_Contact(&con);
default :
printf(" Wrong selection. Please re select ->\n");
}
} while (input);
return 0;
}
contact.h
#define _CRT_SECURE_NO_WARNINGS 1
#pragma once
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<assert.h>
#include<Windows.h>
#define MAX_NAME 20
#define MAX_AGE 20
#define MAX_PHONENUMBER 20
#define MAX_ADDRESS 20
#define MAX_SEX 10
#define DEFAULT_SZ 3
struct info
{
char name[MAX_NAME];
char sex[MAX_SEX];
char phone[MAX_PHONENUMBER];
char address[MAX_ADDRESS];
int age;
};
struct contact
{
struct info* data;
int sz;
int capacity;
};
// Initialize address book
void Init_Contact(struct contact* pf);
// Determine whether the address book needs to be expanded
void Check_Capacity(struct contact* pf);
// Add a Contact
void Add_Contact(struct contact* pf);
void Show_Contact(struct contact* pf);// Print address book
void Del_Contact(struct contact* pf);// Delete Contact
void Search_Contact(struct contact* pf);// Find contacts
void Modify_Contact(struct contact* pf);// Modify contact
void Clear_Contact(struct contact* pf);// Format address book
void Sort_Contact(struct contact* pf);// Sort contacts in the address book
void Save_Contact(struct contact* pf);// Save the contents of the address book to a file
contact.c
Focus on two functions
1, Save the contents of the address book to a file
Storage uses binary storage :
Because the difference between a text file and a binary file is just the difference in encoding , So their advantages and disadvantages are the advantages and disadvantages of coding , Look for a coded book and it will be clear . It is generally believed , Text file encoding is based on character length , It's easier to decode ; Binary encoding is variable length , So it's flexible , Storage utilization is higher , It's harder to decode ( Different binary file formats , There are different ways of decoding ). About space utilization , think about it , Binary files can even use a bit to represent a meaning ( Bit operation ), And any meaning of the text file is at least one character
That is, there is no conversion time in the storage ( Don't encode or decode , Write the value directly ), So we use binary storage . Other words only need to understand fwrite and fread That's all right.
void Save_Contact(struct contact* pf)// Save the contents of the address book to a file
{
assert(pf);
FILE* ps = fopen("contact.txt", "wb");
if (ps == NULL)
{
printf(" File opening failure \n");
return;
}
int i = 0;
for (i = 0; i < pf->sz; i++)
{
fwrite(&(pf->data[i]), sizeof(struct info), 1, ps);// Write the structure data to the file
}
printf(" Address book saved successfully !\n");
fclose(ps);
ps = NULL;
}
2, Initialize address book
When initializing the address book, you should import the contents of the address book in the file into the structure , Because it doesn't rule out checking the address book at the beginning .
void Init_Contact(struct contact* pf)// To initialize the address book, you also need to import the contents of the file into the structure
{
pf->data = (struct info*)malloc(sizeof(struct info) * 3);
if (pf->data == NULL)
{
printf(" Address book initialization error \n");
return 0;
}
pf->sz = 0;
pf->capacity = DEFAULT_SZ;
FILE* ps = fopen("contact.txt", "rb");
if (ps == NULL)
{
printf(" File opening failure \n");
return;
}
while (fread(&(pf->data[pf->sz]), sizeof(struct info), 1, ps))
{
Check_Capacity(pf);
pf->sz++;
}
}
complete contact.c Code
#define _CRT_SECURE_NO_WARNINGS 1
#include"contact.h"
void Init_Contact(struct contact* pf)// To initialize the address book, you also need to import the contents of the file into the structure
{
pf->data = (struct info*)malloc(sizeof(struct info) * 3);
if (pf->data == NULL)
{
printf(" Address book initialization error \n");
return 0;
}
pf->sz = 0;
pf->capacity = DEFAULT_SZ;
FILE* ps = fopen("contact.txt", "rb");
if (ps == NULL)
{
printf(" File opening failure \n");
return;
}
while (fread(&(pf->data[pf->sz]), sizeof(struct info), 1, ps))
{
Check_Capacity(pf);
pf->sz++;
}
}
void Check_Capacity(struct contact* pf)
{
assert(pf);
if (pf->capacity == pf->sz)
{
// Need to increase capacity
struct inof*cur = (struct info*)realloc(pf->data, (pf->capacity + 2) * sizeof(struct info));
if (cur != NULL)
{
pf->data = cur;
pf->capacity += 2;
printf(" Successful expansion \n");
}
else
{
printf(" Capacity increase failed \n");
}
}
}
void Add_Contact(struct contact* pf)
{
// As long as you add contact information, you have to check whether you need to expand
Check_Capacity(pf);
printf(" Please enter a name :\n");
scanf("%s", &(pf->data[pf->sz].name));
printf(" Please enter gender :\n");
scanf("%s", &(pf->data[pf->sz].sex));
printf(" Please enter age :\n");
scanf("%d", &(pf->data[pf->sz].age));
printf(" Please enter the address :\n");
scanf("%s", &(pf->data[pf->sz].address));
printf(" Please enter : number \n");
scanf("%s", &(pf->data[pf->sz].phone));
pf->sz++;
printf(" Add contact succeeded !\n");
}
void Show_Contact(struct contact* pf)// Print address book
{
if (pf->sz == 0)
{
printf(" Address book is empty !\n");
}
else
{
printf("%-20s\t%-5s\t%-4s\t%-30s\t%-13s\t\n", " full name ", " Gender ", " Age ", " Address ", " number ");
int i = 0;
while (i < pf->sz)
{
// data
printf("%-20s\t%-5s\t%-4d\t%-30s\t%-13s\t\n", pf->data[i].name, pf->data[i].sex,
pf->data[i].age, pf->data[i].address, pf->data[i].phone);
i++;
}
}
}
// Find contacts by name
int find_by_name(struct contact* pf, char* name)
{
int i = 0;
while (i < pf->sz)
{
if (strcmp(pf->data[i].name, name) == 0)
return i;
}
return -1;
}
void Del_Contact(struct contact* pf)// Delete Contact
{
if (pf->sz == 0)
{
printf(" Address book is empty , Cannot delete !\n");
}
else
{
char name[MAX_NAME];
printf(" Please enter the name of the contact to be deleted \n");
scanf("%s", name);
int pos = find_by_name(pf,name);
if (pos == -1)
{
printf(" The contact does not exist , Please re-enter \n");
}
else
{
for (int j = pos; j < pf->sz - 1; j++)
pf->data[j] = pf->data[j + 1];
pf->sz--;
printf(" Delete contact successfully !\n");
}
}
}
void Search_Contact(struct contact* pf)
{
if (pf->sz == 0)
{
printf(" Address book is empty , Can't find !\n");
}
else
{
char name[MAX_NAME];
printf(" Please enter the name of the contact to be deleted \n");
scanf("%s", name);
int pos = find_by_name(pf, name);
if (pos == -1)
{
printf(" The contact does not exist , Please find again \n");
}
else
{
printf("%-20s\t%-5s\t%-4s\t%-30s\t%-13s\t\n", " full name ", " Gender ", " Age ", " Address ", " number ");
printf("%-20s\t%-5s\t%-4d\t%-30s\t%-13s\t\n", pf->data[pos].name, pf->data[pos].sex,
pf->data[pos].age, pf->data[pos].address, pf->data[pos].phone);
}
}
}
void Modify_Contact(struct contact* pf)// Modify contact
{
char name[MAX_NAME];
printf(" Please enter the name of the contact to be modified :");
scanf("%s", name);
int pos = find_by_name(pf,name);
if (pos == -1)
{
printf(" The contact does not exist , Please re-enter \n");
return;
}
else
{
printf(" Please enter a name :");
scanf("%s", pf->data[pos].name);
printf(" Please enter gender :");
scanf("%s", pf->data[pos].sex);
printf(" Please enter age :");
scanf("%d", &pf->data[pos].age);
printf(" Please enter the address :");
scanf("%s", pf->data[pos].address);
printf(" Please enter the number :");
scanf("%s", pf->data[pos].phone);
printf(" Contact modified successfully !\n");
}
}
void Clear_Contact(struct contact* pf)// Format address book
{
memset(pf->data, 0, sizeof(pf->data));
pf->sz = 0;
printf(" Format successful !\n");
}
int Compare_by_name(const void* e1, const void* e2)
{
return strcmp(((struct info*)e1)->name, ((struct info*)e2)->name);
}
int Compare_by_age(const void* e1, const void* e2)
{
return ((struct info*)e1)->age - ((struct info*)e2)->age;
}
int Compare_by_address(const void* e1, const void* e2)
{
return strcmp(((struct info*)e1)->address, ((struct info*)e2)->address);
}
void Sort_Contact(struct contact* pf)// Sort contacts in the address book
{
printf(" Please select sort by 1: full name 2: Age 3: Home address \n");
int input = 0;
scanf("%d", &input);
switch (input)
{
case 1:
qsort(pf->data, pf->sz, sizeof(pf->data[0]), Compare_by_name);
printf(" Sort success !\n");
break;
case 2:
qsort(pf->data, pf->sz, sizeof(pf->data[0]), Compare_by_age);
printf(" Sort success !\n");
break;
case 3:
qsort(pf->data, pf->sz, sizeof(pf->data[0]), Compare_by_address);
printf(" Sort success !\n");
break;
}
}
void Save_Contact(struct contact* pf)// Save the contents of the address book to a file
{
assert(pf);
FILE* ps = fopen("contact.txt", "wb");
if (ps == NULL)
{
printf(" File opening failure \n");
return;
}
int i = 0;
for (i = 0; i < pf->sz; i++)
{
fwrite(&(pf->data[i]), sizeof(struct info), 1, ps);// Write the structure data to the file
}
printf(" Address book saved successfully !\n");
fclose(ps);
ps = NULL;
}
In fact, most of the code of the address book is not very difficult , But the storage of files can be appropriately referred to hh
边栏推荐
- Installation of ROS gazebo related packages
- YYGH-10-微信支付
- QT获取某个日期是第几周
- [multithreading] the main thread waits for the sub thread to finish executing, and records the way to execute and obtain the execution result (with annotated code and no pit)
- PowerBI中导出数据方法汇总
- bedtools使用教程
- Esp32 audio frame esp-adf add key peripheral process code tracking
- Develop scalable contracts based on hardhat and openzeppelin (II)
- ESP32存储配网信息+LED显示配网状态+按键清除配网信息(附源码)
- 揭露数据不一致的利器 —— 实时核对系统
猜你喜欢

2022年4月17日五心红娘团队收获双份喜报

Seriation in R: How to Optimally Order Objects in a Data Matrice

Tidb DM alarm DM_ sync_ process_ exists_ with_ Error troubleshooting

GGPlot Examples Best Reference

Amazon cloud technology community builder application window opens

Mmrotate rotation target detection framework usage record

八大排序汇总

2022年遭“挤爆”的三款透明LED显示屏

6. Introduce you to LED soft film screen. LED soft film screen size | price | installation | application

How to Create a Nice Box and Whisker Plot in R
随机推荐
Order by注入
HOW TO EASILY CREATE BARPLOTS WITH ERROR BARS IN R
map集合赋值到数据库
Map set assignment to database
CTF record
Cluster Analysis in R Simplified and Enhanced
Visualization of chip SEQ data by deeptools
Is it safe to open a stock account online? I'm a novice, please guide me
时间格式化显示
[idea] use the plug-in to reverse generate code with one click
Homer预测motif
Wechat applet uses Baidu API to achieve plant recognition
JS -- take a number randomly from the array every call, and it cannot be the same as the last time
FLESH-DECT(MedIA 2021)——一个material decomposition的观点
在连接mysql数据库的时候一直报错
Esp32 audio frame esp-adf add key peripheral process code tracking
Tidb DM alarm DM_ sync_ process_ exists_ with_ Error troubleshooting
SSRF
Eight sorting summaries
由粒子加速器产生的反中子形成的白洞