Analog implementation Contacts < three > (file stream)

Source: Internet
Author: User
Tags strcmp

# Use file manipulation functions to implement contacts/*
file Stream Implementation Address Book description: We usually test code input data, but once each time the program is finished, the data will be gone, such as test communication
record, enter a lot of information to find a place to change, it is necessary to end the program, the next time to re-enter, very troublesome right, file stream implementation of
The advantage is that you can save our input data to a file each time, the next time directly from the file read, save a lot of trouble!
*/

@ Analog Implementation Contacts < one > (static implementation) Blog link: http://blog.csdn.net/bitboss/article/details/51374654
@ Analog Implementation Contacts < two > (Dynamic Implementation) Blog link: http://blog.csdn.net/bitboss/article/details/51417430

< a > file manipulation function in code(only about function function, function parameter part details please understand);

@ fopen Function Description: header file <stdlib.h>;

function Prototypes:FILE * fopen (const char * path,const char * mode);
<1> Path is the name of the file to open, mode is opened in the form (mode has many forms);
<2> Open file to have the corresponding fclose (const char *path) function to close the file;
return Value:when the file is opened successfully,meansto the flow'sFile Pointerswill be returned. Returns null if the file fails to open andError codeexist
errnothe.
In general , after opening the file will do some file read or write action, if the file failed to open, the next read and write actions will not be smooth, so
generally after the fopen () for error judgment and processing.

@ PERROR Function Description: header file <stdlib.h>;
Perror (s) is used to output the cause of an error in the previous function to a standard device (stderr). The string that the parameter S refers to is printed first, followed by
Add the error reason string. The reason for this error is based on the global variable errno (the argument here does notexactly, errno is a macro that returns the value of the left value to determine the
the output string.         There is a errno variable in the library function, and each errno value corresponds to the type of error represented by a string. When you call the "some" function error, the function has been
the value of errno has been reset. The Perror function is just some of the information you enteroutput along with the error corresponding to the current errno.

@ fwrite Function Description: header file <stdlib.h>;
function Prototypes: size_t fwrite (const void* buffer, size_t size, size_t count, file* stream);
function function:fwrite is a C language function that points to a file to write a data block.
Note: This function operates on files in binary form, not limited to text files
return Value: returns the actual writeData Blocknumber
(1) Buffer: is a Pointers , for Fwrite, is to obtain the address of the data; (2) Size: The number of single bytes to write to the content; (3) Count: The size byte to be written to Data Item the number of; (4) stream: Target File Pointers ; (5) Returns the number of data items actually written to count.

@ Fread Function Description: header file <stdlib.h>;
function Prototypes: size_t fread (void * Buffer , size_t size , size_t Count , FILE * Stream ) ;
function Function:
Fread is a function. Reads data from a file stream, reading up to count elements, each element size byte, if the call succeeds in returning the actual read
taken tothe number of elements, if unsuccessful or read to the end of the file, returns 0.

Parameters:
Bufferused to receive data.memory Address
sizeThe number of bytes per data item to read, the unit isbytes
Countto readcount data items, each data item is a size byte.
Streaminput Streamfreadreturn valuethe number of elements actually read. If the return value is the same as Count, the end of the file or an error may occur. Get error messages or check from ferror and feof
The end of the file is reached.  

< two > code implementation
# Custom header File "address.h" section
#pragma warning (disable:4996)//To eliminate scanf warnings, #ifndef __address_h__//prevent redefinition; #define __address_h__#include<stdio.h > #include <stdlib.h> #include <string.h> #define NAME_MAX 20#define sex_max 4#define Home_max 10#define Tel_max 13#define Member_max 2//just started phone book capacity//Name, gender, age, phone, address typedef struct PERSON{CHAR Name[name_max];char Sex[sex_max]; int Age;char Tel[tel_max];char Home[home_max];} person;//Address Book member structure, typedef struct COUNT{PERSON *people;int size;//determine the current number of contacts; int capacity;//telephone volume;}count,*con;// Pointers are used to accept struct pointers within functions; enum op{exit,add,del,search,mod,show,sort,empty};void exit (con con);//exit function; void ADD (con con);// New member: void Del (con con),//delete member, void search (con con),//Find member, void Mod (con con);//modify member; void show (con con);//Show All members; void Empty (con con);//clear Address Book, void sort (con con);//Sort all members; void Check (con con);//select function; void _print (); void SaveData (con con);// Save data to file stream, void DownLoad (con con),//read saved data from the file stream,//void (*str[8]) (con con) = {Exit,add,del,search,mod,show,sort, The empty};//function pointer array is much more convenient than the switch statement! #endiF//__address_h__ 


# Main Function Main section
#include "address.h" int main () {count Con = {0}; Con.size = 0;//size must be initialized to 0;con.capacity  = Member_max; Con.people  = (person *) malloc (Member_max *sizeof (person));/* Pay attention to the free () corresponding to malloc, the  subject is directly in the launch function free;*/if ( Con.people = = NULL)//whether to open up a successful judgment; printf ("Out of memory\n"); else{    DownLoad (&con);//Read data from a file; while (1) {Check ( &con);}} System ("pause"); return 0;}


# Function function Implementation section
#include "address.h"//Name, gender, age, phone, address void _print () {printf ("*************************\n");p rintf ("1. Add contact information \ n");    printf ("2. Delete the specified contact information \ n");    printf ("3. Find specified contact information \ n");    printf ("4. Modify the specified contact information \ n");    printf ("5. Show all contact information \ n");p rintf ("6. Sort all contact information \ n");      printf ("7. Clear all contacts \ n");p rintf ("0. Exit \ n ");p rintf (" *************************\n ");p rintf (" Please select function (0-7): >\n ");} /* Because the lookup function is used by several functions, a find function is closed separately, */void judge_full (con con) {if (con->size = = con->capacity) {/* Current number of people has reached the maximum address book capacity , the ReAlloc function is used for the expansion, */person *tmp = (person *) realloc (con->people, (con->capacity +3) *sizeof (person)); if (tmp = = NULL) printf ("Out of memory\n"); elsecon->people = tmp; (con->capacity) + = 3;} Determine if the address book overflows;}int find (Con con, char arr[])//common lookup function; {int i =0;for (; i<con->size;i++) {if (strcmp (con->people [i] . name,arr) = = 0) return i;} return-1;} void add (con con)//add member; {if (con->size = = con->capacity) {/* The current number of people has reached the maximum Address book capacity, then expansion, with realloc function; */person *tmp = ( Person *) ReAlloc (con->people, (con->capacity +3) *sizeof (person)), if (tmp = = NULL) printf ("Out of memory\n"); elsecon->people = tmp; (con->capacity) + = 3;} Determine if the address book overflows; printf ("Ready to add a new member: >\n");p rintf ("Please enter name: \ n"); scanf ("%s",& (Con->people[con->size].name)) ;p rintf ("Please enter gender: \ n"), scanf ("%s",& (con->people[con->size].sex));p rintf ("Please enter Age: \ n"); scanf ("%d",& ( con->people[con->size].age));p rintf ("Please enter phone: \ n"); scanf ("%s",& (Con->people[con->size].tel)); printf ("Please enter address: \ n"); scanf ("%s",& (con->people[con->size].home));p rintf ("saved successfully! \ n ");  con->size++;//Note: For each additional member, the total number of contacts size is +1;}void Del (con con)//delete member; {int ret = 0;char Name[20] = {0};if (con->size = = 0) {printf ("Pro!") The current address Book is empty! \ n "); return;} printf ("Please enter the name of the person to be deleted: \ n"); scanf ("%s", &name); ret = find (con,name);/* The method of deletion is to place the last member on the deleted member position; NOTE: You cannot forget size--;*/ if (ret>=0) {Con->people[ret] = con->people[con->size-1];(con->size)--;p rintf ("Delete succeeded! \ n ");} Elseprintf ("Did not find the object to delete! \ n ");} void search (con con)//lookup member; Call the find function directly; {int ret = 0;char Name[20] = {0};printf ("Please enter the name of the person to be queried: \ n"), scanf ("%s", &name), ret = Find (Con,name), if (ret>=0) {printf ("%10s\t%4s\t%3s\t%13s\t% 10s\n "," name "," Sex "," Age "," tel "," address ");p rintf ("%10s\t%4s\t%3d\t%13s\t%10s\n ", Con->people [Ret].name, con- >people [Ret].sex, Con->people [Ret].age, Con->people [Ret].tel, Con->people [Ret].home];} elseprintf ("Didn't find this address book buddy! \ n ");} void Mod (con con)//change member; {int i = 0;int ret = 0;char name[20] = {0};char *ptr[] = {"Name", "Sex", "Age", "tel", "address"};//each time Change the individual content of a member; printf ("Please enter the contact you want to modify: \ n"); scanf ("%s", &name); ret = find (con,name);//Call lookup function; if (ret>=0) {int ages = 0; Char mod[20] = {0};int sel = 0;printf ("Please enter an option to modify: \ n");p rintf ("1.name\n2.sex\n3.age\n4.tel\n5.adress\n"); scanf ("%d", &sel);p rintf ("Please enter \ n");//This block selects the switch statement; it is easier to read; switch (SEL) {case 1:scanf ("%s", &mod); strcpy (con- >people [Ret].name,mod];p rintf ("modified successfully! \ n "); Break;case 2:scanf ("%s ", &mod); strcpy (con->people [Ret].sex, MoD);p rintf (" modified successfully! \ n "); Break;case 3:scanf ("%d ", &ages); Con->people [ret].age = ages;printf ("Modified successfully! \ n "); Break;case 4:scanf ("%s ", &mod); strcpy (con->people [Ret].tel, MoD);p rintf (" modified successfully! \ n "); Break;case 5:scanf ("%s ", &mod); strcpy (con->people [Ret].home, MoD);p rintf (" modified successfully! \ n "); break;default:printf (" Modification failed! \ n "); break;}} ELSEPRINTF ("no member!\n");}   void show (con con)//Show all members; {int i = 0; printf ("%10s\t%4s\t%3s\t%13s\t%10s\n", "name", "Sex", "Age", "tel", "address");//loop print each address book member; for (; I < con->size ;   i++) {printf ("%10s\t%4s\t%3d\t%13s\t%10s\n", Con->people [I].name, Con->people [I].sex, Con->people [I].age], Con->people [I].tel, Con->people [I].home];}} void empty (con con)//emptying contacts; {/* Empty contacts only need to change the total number of contacts to 0;*/con->size = 0;printf ("Address Book is empty! \ n ");} void sort (con con)//Sort all contacts; {/* bubbles sort all members by name; */int flag = 0;int i = 0;int j = 0;for (i = 0; i < con->size-1; i++) {FL AG = 1;for (j = 0;j < (con->size)-i-1;j++) {if (strcmp (Con->people[j].name, Con->people [j+1].name)) > 0) {p Erson tmp = con->people[j]; Con->people[j] = con->people[j+1]; Con->people[j+1] = Tmp;flag = 0;}} if (flag==1) break;}} void exit (con con)//Exit function; {SaveData (con); free (con->people); Con->people = null;exit (0);} Defines an array of function pointers to facilitate the invocation of functions! void (*str[8]) (con con) = {exit,add,del,search,mod,show,sort,empty};void Check (con con)//select function; {int select = ' 0 ';//if ( Con->size = = con->capacity)//{//person *tmp = (person *) realloc (con->people, con->capacity +3);//if (tmp = = N ULL)//printf ("Out of memory\n");//else//con->people = tmp; Con->capacity + = 3;//}_print (); scanf ("%d", &select); if (select==0 | | select==1| | select==2| | select==3| | select==4| | select==5| | select==6 | | select==7) Str[select] (con);/* If you do not make a while loop in the main function and call yourself directly in the check function, the drawback is that the check function is called repeatedly recursively, causing the stack to overflow; check (Con); */else{ printf ("The input format is wrong! \ n ");}} void SaveData (con con)//save data to file stream {/*savedata Call before exiting the program; */int i = 0; FILE *pfwrite = fopen ("Message.txt", "w"), if (Pfwrite = = NULL) {perror ("Open File for write"); exit (exit_failure);} for (i = 0; i < con->size;i++) {fwrite (& (Con->people[i]), sizeof (person), 1, pfwrite);} Fclose (pfwrite);} void DownLoad (con con)//read data from a file {//download is called after a good con has just been created; the main function part;/* Here a temporary TMP is created to prevent overflow due to no increase in capacity ; So we temporarily create a TMP, put the content read from the file in the TMP, and then determine whether the current need to increase capacity, and then the contents of the TMP into our data block; */int i = 0;person tmp = {0}; FILE *pfread = fopen ("Message.txt", "R"), if (Pfread = = NULL) {perror ("Open file for read"); exit (exit_failure);} while (Fread (&tmp,sizeof (person), 1, Pfread)) {judge_full (Con); con->people [i] = tmp;i++; Con->size ++;//Each time a data is read, the current number of data size increases by one;}}

Ps: Do not force yourself a, how to know how good they are!
thanks!


Analog implementation Contacts < three > (file stream)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.