#define FILENAME "contacts.dat"
// Add contact
void addContact() {
struct Contact c;
FILE *fp = fopen(FILENAME, "ab");
if(!fp) { printf("Error opening file.\n"); return; }
printf("Enter Name: "); scanf(" %[^\n]", c.name);
printf("Enter Phone: "); scanf(" %[^\n]", c.phone);
printf("Enter Email: "); scanf(" %[^\n]", c.email);
fwrite(&c, sizeof(c), 1, fp);
fclose(fp);
printf("Contact added successfully!\n");
}
// Display all contacts
void displayContacts() {
struct Contact c;
FILE *fp = fopen(FILENAME, "rb");
if(!fp) { printf("No records found.\n"); return; }
printf("\nName\tPhone\tEmail\n");
while(fread(&c, sizeof(c), 1, fp)) {
printf("%s\t%s\t%s\n", c.name, c.phone, c.email);
}
fclose(fp);
}
// Search contact by name
void searchContact() {
char searchName[50];
struct Contact c;
printf("Enter Name to search: "); scanf(" %[^\n]", searchName);
FILE *fp = fopen(FILENAME, "rb");
if(!fp) { printf("No records found.\n"); return; }
int found = 0;
while(fread(&c, sizeof(c), 1, fp)) {
if(strcmp(c.name, searchName) == 0) {
printf("Name: %s\nPhone: %s\nEmail: %s\n", c.name, c.phone, c.email);
found = 1;
break;
}
}
if(!found) printf("Contact not found.\n");
fclose(fp);
}
// Update contact
void updateContact() {
char searchName[50];
struct Contact c;
FILE *fp = fopen(FILENAME, "rb+");
if(!fp) { printf("No records found.\n"); return; }
printf("Enter Name to update: "); scanf(" %[^\n]", searchName);
int found = 0;
while(fread(&c, sizeof(c), 1, fp)) {
if(strcmp(c.name, searchName) == 0) {
printf("Enter new Phone: "); scanf(" %[^\n]", c.phone);
printf("Enter new Email: "); scanf(" %[^\n]", c.email);
fseek(fp, -sizeof(c), SEEK_CUR);
fwrite(&c, sizeof(c), 1, fp);
printf("Contact updated successfully!\n");
found = 1;
break;
}
}
if(!found) printf("Contact not found.\n");
fclose(fp);
}
// Delete contact
void deleteContact() {
char searchName[50];
struct Contact c;
FILE *fp = fopen(FILENAME, "rb");
FILE *temp = fopen("temp.dat", "wb");
if(!fp || !temp) { printf("File error.\n"); return; }
printf("Enter Name to delete: "); scanf(" %[^\n]", searchName);
int found = 0;
while(fread(&c, sizeof(c), 1, fp)) {
if(strcmp(c.name, searchName) == 0) {
found = 1;
continue; // skip copying
}
fwrite(&c, sizeof(c), 1, temp);
}
fclose(fp);
fclose(temp);
remove(FILENAME);
rename("temp.dat", FILENAME);
if(found) printf("Contact deleted successfully!\n");
else printf("Contact not found.\n");
}