Skip to content
StudyFame

Contact Book Project in C

Every phone has a contact list: names, phone numbers and emails, kept in order and searchable in a second. In this project you build a contact book (phonebook) in C. This time the data goes into a text file, one contact per line, so you can open it in Notepad and read it yourself.

You will add contacts with phone number validation, list them, search by part of a name, delete a contact, and finally sort all contacts alphabetically with qsort.

What You Will Learn

  • How to store records in a text file with a separator.
  • How to read separated fields with fscanf and %[^|].
  • How to validate a phone number character by character.
  • How to search names without caring about upper or lower case.
  • How to delete a line from a text file.
  • How to load records into an array and sort them.

Contact Book Project in C Explained

Exam definition: In a delimited text file, each record is stored on one line, and its fields are separated by a delimiter character such as | or , (CSV). Records are written with fprintf and read back with fscanf using scan sets like %[^|] ("read up to the next |"). Text files are human-readable and portable, but slower to search and update than binary files with fixed-size records.

Memory trick: A delimited file is a diary page where each friend gets one line: Name | Phone | Email. The | is the pencil line between columns. To read a friend, you read up to the first line, then up to the next, then to the end of the row.

Syntax: Writing and Reading a Delimited File

/* write one contact per line */
fprintf(fp, "%s|%s|%s\n", c.name, c.phone, c.email);

/* read one contact back: name up to '|', phone up to '|', email up to newline */
while (fscanf(fp, " %29[^|]|%14[^|]|%39[^\n]", c.name, c.phone, c.email) == 3)
{
    ...
}
contacts.txt
Aditi Verma|9876543210|[email protected]
Rahul Mehta|9123456780|[email protected]

Example 1: Contact Book with a Text File

#include <stdio.h>
#include <string.h>
#include <ctype.h>

#define FILE_NAME "contacts.txt"

struct contact
{
    char name[30];
    char phone[15];
    char email[40];
};

int valid_phone(const char *p)
{
    int i;
    if (strlen(p) != 10)
        return 0;
    for (i = 0; i < 10; i++)
        if (!isdigit((unsigned char) p[i]))
            return 0;
    return 1;
}

int read_contact(FILE *fp, struct contact *c)
{
    return fscanf(fp, " %29[^|]|%14[^|]|%39[^\n]", c->name, c->phone, c->email) == 3;
}

void add_contact(void)
{
    struct contact c;
    FILE *fp;

    printf("Name : ");
    scanf(" %29[^\n]", c.name);
    printf("Phone: ");
    scanf(" %14s", c.phone);
    if (!valid_phone(c.phone))
    {
        printf("Invalid phone. Enter exactly 10 digits.\n");
        return;
    }
    printf("Email: ");
    scanf(" %39s", c.email);
    fp = fopen(FILE_NAME, "a");
    if (fp == NULL) return;
    fprintf(fp, "%s|%s|%s\n", c.name, c.phone, c.email);
    fclose(fp);
    printf("Contact saved.\n");
}

void list_contacts(void)
{
    struct contact c;
    FILE *fp = fopen(FILE_NAME, "r");
    int n = 0;
    if (fp == NULL) { printf("No contacts.\n"); return; }
    while (read_contact(fp, &c))
        printf("%d. %-12s %s  %s\n", ++n, c.name, c.phone, c.email);
    fclose(fp);
}

/* case-insensitive "does name contain part?" */
int name_has(const char *name, const char *part)
{
    char a[30], b[30];
    int i;
    for (i = 0; name[i] && i < 29; i++) a[i] = (char) tolower((unsigned char) name[i]);
    a[i] = '\0';
    for (i = 0; part[i] && i < 29; i++) b[i] = (char) tolower((unsigned char) part[i]);
    b[i] = '\0';
    return strstr(a, b) != NULL;
}

void search_contacts(void)
{
    struct contact c;
    char part[30];
    FILE *fp = fopen(FILE_NAME, "r");
    int found = 0;

    printf("Search name: ");
    scanf(" %29[^\n]", part);
    if (fp == NULL) return;
    while (read_contact(fp, &c))
        if (name_has(c.name, part))
        {
            printf("  %s - %s\n", c.name, c.phone);
            found++;
        }
    printf("%d contact(s) found\n", found);
    fclose(fp);
}

void delete_contact(void)
{
    struct contact c;
    char name[30];
    FILE *fp = fopen(FILE_NAME, "r"), *tmp;
    int deleted = 0;

    printf("Exact name to delete: ");
    scanf(" %29[^\n]", name);
    if (fp == NULL) return;
    tmp = fopen("temp.txt", "w");
    if (tmp == NULL) { fclose(fp); return; }
    while (read_contact(fp, &c))
    {
        if (strcmp(c.name, name) == 0)
            deleted = 1;
        else
            fprintf(tmp, "%s|%s|%s\n", c.name, c.phone, c.email);
    }
    fclose(fp);
    fclose(tmp);
    remove(FILE_NAME);
    rename("temp.txt", FILE_NAME);
    printf(deleted ? "Contact deleted.\n" : "No contact with that name.\n");
}

int main(void)
{
    int choice;
    while (1)
    {
        printf("\n1.Add 2.List 3.Search 4.Delete 0.Exit\nChoice: ");
        if (scanf("%d", &choice) != 1 || choice == 0)
            break;
        switch (choice)
        {
        case 1: add_contact(); break;
        case 2: list_contacts(); break;
        case 3: search_contacts(); break;
        case 4: delete_contact(); break;
        default: printf("Invalid choice\n");
        }
    }
    printf("Bye!\n");
    return 0;
}

Output

1.Add 2.List 3.Search 4.Delete 0.Exit
Choice: 1
Name : Rahul Mehta
Phone: 9123456780
Email: [email protected]
Contact saved.

1.Add 2.List 3.Search 4.Delete 0.Exit
Choice: 1
Name : Aditi Verma
Phone: 98765
Invalid phone. Enter exactly 10 digits.

1.Add 2.List 3.Search 4.Delete 0.Exit
Choice: 1
Name : Aditi Verma
Phone: 9876543210
Email: [email protected]
Contact saved.

1.Add 2.List 3.Search 4.Delete 0.Exit
Choice: 1
Name : Rohan Das
Phone: 9988776655
Email: [email protected]
Contact saved.

1.Add 2.List 3.Search 4.Delete 0.Exit
Choice: 2
1. Rahul Mehta  9123456780  [email protected]
2. Aditi Verma  9876543210  [email protected]
3. Rohan Das    9988776655  [email protected]

1.Add 2.List 3.Search 4.Delete 0.Exit
Choice: 3
Search name: ro
  Rohan Das - 9988776655
1 contact(s) found

1.Add 2.List 3.Search 4.Delete 0.Exit
Choice: 4
Exact name to delete: Rahul Mehta
Contact deleted.

1.Add 2.List 3.Search 4.Delete 0.Exit
Choice: 2
1. Aditi Verma  9876543210  [email protected]
2. Rohan Das    9988776655  [email protected]

1.Add 2.List 3.Search 4.Delete 0.Exit
Choice: 0
Bye!

Code Explanation

  1. Each contact is written as one line: Name|Phone|Email. Opening in "a" mode adds new lines at the end.
  2. read_contact() reads one line back: %29[^|] takes everything up to a | (so names can contain spaces), the | in the format skips the separator, and %39[^\n] takes the rest of the line. The leading space skips the previous newline.
  3. valid_phone() checks the length is exactly 10 and every character is a digit with isdigit(). "98765" is rejected before an email is even asked.
  4. name_has() copies both strings in lower case and uses strstr, so searching "ro" finds "Rohan Das" but not "Rahul". "Aditi Verma" contains no "ro", so only one match is shown.
  5. Deleting works like the binary version: copy every other line into temp.txt, then remove and rename.

How Text and Binary Storage Compare

PointText file (this project)Binary file (student/bank projects)
Readable in NotepadYesNo
Write / readfprintf / fscanf, fgetsfwrite / fread
Record sizeVaries per lineFixed (sizeof struct)
Update in placeNot practical; rewrite the filefseek + fwrite
Jump to record kMust read lines one by onefseek to k × size
Portable between computersVeryDepends on struct layout

A delimiter must never appear inside the data. If a name could contain |, choose another separator or escape it. That is exactly the problem CSV quoting rules solve.

Example 2: Sort Contacts Alphabetically

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX 100

struct contact
{
    char name[30];
    char phone[15];
    char email[40];
};

int by_name(const void *a, const void *b)
{
    return strcmp(((const struct contact *) a)->name, ((const struct contact *) b)->name);
}

int main(void)
{
    struct contact list[MAX];
    FILE *fp = fopen("contacts.txt", "w");
    int n = 0, i;

    if (fp == NULL) return 1;
    fputs("Rohan Das|9988776655|[email protected]\n", fp);
    fputs("Aditi Verma|9876543210|[email protected]\n", fp);
    fputs("Meena Iyer|9012345678|[email protected]\n", fp);
    fputs("Kabir Khan|9090909090|[email protected]\n", fp);
    fclose(fp);

    fp = fopen("contacts.txt", "r");
    if (fp == NULL) return 1;
    while (n < MAX &&
           fscanf(fp, " %29[^|]|%14[^|]|%39[^\n]", list[n].name, list[n].phone, list[n].email) == 3)
        n++;
    fclose(fp);

    qsort(list, n, sizeof list[0], by_name);

    printf("Contacts A-Z (%d):\n", n);
    for (i = 0; i < n; i++)
        printf("%c  %-12s %s\n", list[i].name[0], list[i].name, list[i].phone);

    fp = fopen("contacts.txt", "w");          /* save in sorted order */
    if (fp == NULL) return 1;
    for (i = 0; i < n; i++)
        fprintf(fp, "%s|%s|%s\n", list[i].name, list[i].phone, list[i].email);
    fclose(fp);
    printf("File saved in sorted order.\n");
    remove("contacts.txt");
    return 0;
}

Output

Contacts A-Z (4):
A  Aditi Verma  9876543210
K  Kabir Khan   9090909090
M  Meena Iyer   9012345678
R  Rohan Das    9988776655
File saved in sorted order.
  • All contacts are loaded into an array of structures, sorted in memory, then written back.
  • qsort calls by_name, which compares two names with strcmp (alphabetical order, upper case before lower case).
  • For a few hundred contacts, "load, sort, save" is simple and fast. Huge datasets use databases or indexes instead.

Important Points to Remember

  • A text record = one line with fields separated by a delimiter (| or ,).
  • Read fields with %[^|] and the last field with %[^\n]; always give a width.
  • Validate input (10 digits) before saving.
  • Case-insensitive search: convert both strings with tolower, then use strstr.
  • Deleting or editing a text record means rewriting the file (via a temporary file).
  • Sort records by loading them into an array and using qsort with strcmp.

Common Mistakes Beginners Make

MistakeWhat happensFix
Storing the phone as int10-digit numbers overflow; leading zeros lostStore phone numbers as strings
%s for the name in fscanf"Rahul Mehta" breaks the recordUse %29[^|]
No leading space in " %29[^|]"The second record starts with '\n'Add the space
Delimiter appears in the dataFields shift; records breakPick a safe delimiter or escape it
Opening with "w" to addAll contacts erasedUse "a"

Contact Book Practice Questions

  1. What is a delimited text file? Give an example line.
  2. What does %[^|] mean in a scanf format?
  3. Why is a phone number stored as a string, not an int?
  4. How is a contact deleted from a text file?
  5. Give two advantages of text files and two of binary files.
Show answers
  1. A file where each record is a line and fields are separated by a delimiter, e.g. Aditi Verma|9876543210|[email protected].
  2. Read every character that is not | (a scan set), stopping before the next |.
  3. 10-digit numbers can exceed int's range, leading zeros would be lost, and no arithmetic is done on them.
  4. Copy every other line to a temporary file, delete the original and rename the temporary file.
  5. Text: human-readable, portable. Binary: fixed-size records allow fast seek/update, and data is compact.

Coding Exercise

Write a function int valid_email(const char *e) that returns 1 if the email has exactly one @, at least one character before it, and a . somewhere after it. Test it on "[email protected]", "aditi.mail.com", "@mail.com", "a@[email protected]" and "rahul@mailcom".

Show solution
#include <stdio.h>
#include <string.h>

int valid_email(const char *e)
{
    const char *at = strchr(e, '@');
    if (at == NULL || at == e)            /* no @, or nothing before it */
        return 0;
    if (strchr(at + 1, '@') != NULL)      /* a second @ */
        return 0;
    return strchr(at + 1, '.') != NULL;   /* a dot after @ */
}

int main(void)
{
    const char *tests[] = {"[email protected]", "aditi.mail.com", "@mail.com", "a@[email protected]", "rahul@mailcom"};
    int i;
    for (i = 0; i < 5; i++)
        printf("%-15s %s\n", tests[i], valid_email(tests[i]) ? "valid" : "invalid");
    return 0;
}
[email protected]  valid
aditi.mail.com  invalid
@mail.com       invalid
a@[email protected]       invalid
rahul@mailcom   invalid

Quick Quiz: Contact Book Project (MCQ)

  1. Which mode adds a contact to the end of a text file?

    A) "r"   B) "w"   C) "a"   D) "rb"

  2. In fscanf(fp, "%29[^|]", s), reading stops at:

    A) A space   B) The character |   C) A digit   D) 29 lines

  3. Best data type for a phone number:

    A) int   B) float   C) char array (string)   D) double

  4. isdigit('7') returns:

    A) 0   B) Non-zero (true)   C) 7 always   D) An error

  5. To sort an array of contacts by name you can use:

    A) qsort with strcmp   B) strstr   C) fseek   D) rand

Show answers
  1. C: "a".
  2. B: the character |.
  3. C: a char array.
  4. B: non-zero (true).
  5. A: qsort with strcmp.

Quick Revision for Exams and Interviews

Read this before your exam. The highlighted words are the answer.

Must-remember facts

Record formatName|Phone|Email, one line
Writefprintf, mode "a"
Read field%[^|]; last field %[^\n]
PhoneStore as a string; check 10 digits with isdigit
Searchtolower + strstr
Delete/editRewrite via a temp file
Sortqsort + strcmp

Frequently asked questions

How do you store contacts in a file in C?
Write each contact as one line with delimited fields using fprintf, and read them back with fscanf scan sets.
How do you read a name with spaces from a file?
Use a scan set like %29[^|] that reads up to the delimiter instead of %s.
Text file or binary file for a phonebook?
Text is readable and portable; binary is better for fast in-place updates of fixed-size records.

Remember

  • Delimited file = diary lines with column marks.
  • Phone numbers are text, not numbers.

Next Topic

Next lesson: Employee Payroll System in C. In the last project you will calculate salaries with allowances, tax and deductions in an employee payroll system.