0
我正在編寫一個地址簿程序。有插入,顯示和刪除選項。插入時,它將輸入數據並將其存儲到文件中。每當我添加新聯繫人時,都會將它們添加到文件中。 將數據保存到文件後,我可以動態分配一個結構地址簿數組來存儲每個聯繫人詳細信息。因此,如果我想要顯示或刪除特定的聯繫人,除了打開文件,比較文件中的每個元素之外,很容易。 根據保存在文件中的聯繫人數量,我們可以動態地爲結構地址簿分配數組並存儲細節。如何動態創建一個結構數組並將其存儲在文件中
#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");
}