【问题标题】:how to dynamically create an array of structure and store the data in file如何动态创建结构数组并将数据存储在文件中
【发布时间】:2011-11-19 12:03:47
【问题描述】:

我正在为地址簿编写一个程序。有插入、显示和删除选项。在插入时,它获取输入数据并将它们存储到文件中。每当我添加新联系人时,它都会将它们添加到文件中。 将数据保存到文件后,我可以动态分配一个结构地址簿数组来存储每个联系人详细信息。因此,如果我想显示或删除特定联系人,除了打开文件、比较文件中的每个元素之外,它会很容易。 根据保存到文件中的联系人数量,我们是否可以为struct addressbook动态分配数组并存储详细信息。

    #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");
    }

【问题讨论】:

    标签: c arrays file data-structures dynamic-memory-allocation


    【解决方案1】:

    您的通讯录应该包含一个联系人列表。因此,最好不要将其与特定的联系方式混为一谈。更好的方法是:

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

    在您的 AddressBook 结构中,您可以将 Struct Contact 的对象存储为链表或数组(如果需要,动态增长)。

    struct AddressBook
    {
      Contact *contacts[MAX_CONTACTS];
    }
    

    每次读入数据时,将其存储到新的Contact 对象中,并将指向该对象的指针存储在数组中。但是如果您的联系人数量很多,不建议将所有联系人都存储在内存中,而是可以对文件进行一些二进制搜索并仅读取所需的联系人块。

    【讨论】:

      猜你喜欢
      • 2017-06-02
      • 2021-01-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多