简体   繁体   中英

how to dynamically create an array of structure and store the data in file

I am writing a program for address book. There are insert, display and delete options. In insertion, it takes input data and stores them to a file. whenever I add new contact it adds them to the file. After saving the data to file, Can i dynamically allocate an array of struct addressbook to store each contact details. So that if I want to display or delete a particular contact it will be easy other than opening a file, comparing each element in the file. Depending upon the number of contacts saved into the file, can we dynamically allocate array for struct addressbook and store the details.

    #define FIRST_NAME_LENGTH  15
    #define LAST_NAME_LENGTH   15
    #define NUMBER_LENGTH      15
    #define ADDRESS_LENGTH     15
    /* Structure defining a name */
    struct Name
    {
      char lastname[LAST_NAME_LENGTH];
      char firstname[FIRST_NAME_LENGTH];
    };

    /* Structure defining a phone record */
    struct addressbook 
    {
      char answer;
      struct Name name;
      char address[ADDRESS_LENGTH];
      char phonenumber[NUMBER_LENGTH];

    };
    struct addressbook a;


    void add_record()
    {
      printf("enter details\n");
      printf("enter lastname of person :\n");
      scanf("%s", a.name.lastname);
      printf("enter firstname of person :\n");
      scanf("%s", a.name.firstname);
      printf("enter address of person :\n");
      scanf("%s", a.address);
      printf("enter phone number of person :\n");
      scanf("%s", a.phonenumber);
      if((fp = fopen(filename,"a+")) == NULL){
        printf("Error opening %s for writing. Program terminated.\n", filename);
        abort();
      }
      fwrite(&a, sizeof(a), 1, fp);                  /* Write to the file */
      fclose(fp);                                     /* close file */
      printf("New record added\n");
    }

Your address book is supposed to hold a list of contacts. So its better not to clutter it with specific Contact details. A better way to do this would be:

struct Contact
{
  struct Name name;
  char address[ADDRESS_LENGTH];
  char phonenumber[NUMBER_LENGTH];
};

In your AddressBook structure you can store objects of Struct Contact either as a linked list or an array( dynamically growing if you need it).

struct AddressBook
{
  Contact *contacts[MAX_CONTACTS];
}

Everytime you read in data, store it into a new Contact object and store the pointer to that object in your array. But if you have large no of contacts, it is not recommended to store all of them in memory, rather you can do some binary search on the file and read only the needed block of contacts.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM