← 返回课程: C programming from scratch

Final project: contact manager saved to a file

视频即将上线

This is the last lesson and you will use almost everything you learned: structs and typedef, dynamic memory with malloc, realloc and free, safe strings, functions, several files with headers, reading and writing files, Makefile and debugging tools. The project is a console contact manager: the program loads an address book from a text file on startup, lets you list, add, search and delete contacts from a menu, and saves the changes on exit. What matters is not that it is big, but that it is correct: no memory leaks, no overflows and every error checked.

Brief and requirements

  • Three modules: contacts.h/contacts.c (the logic) and main.c (the menu), plus a Makefile.
  • Contact stores name (max 49 characters) and phone (max 19) in fixed arrays.
  • ContactList is a dynamic array that grows with realloc (initial capacity 4, doubling).
  • Functions: add, find by name, delete by index, load and save. Each returns an error code that main checks.
  • Format of contacts.txt: one line per contact, name;phone.
  • If contacts.txt does not exist on startup, the book starts empty; invalid lines are skipped with a warning on stderr.
  • Menu: 1 list, 2 add, 3 search, 4 delete, 0 save and exit.
  • Compile with -std=c17 -Wall -Wextra -Wpedantic with no warnings and pass -fsanitize=address,undefined with no reports or leaks.

The contacts module

Start with the header: define the size constants, the two types and the prototypes with a comment about what each function returns. Then implement contacts.c. Notice the safety decisions: contacts_add rejects empty names, names that are too long or contain the ';' separator, copies with snprintf, and only changes the list if realloc succeeded (never assign the result of realloc directly to the original pointer, or you will lose the memory if it fails). We give you the module almost complete so you can focus on main; read it carefully before using it, because you must be able to explain each line.

c
/* ---- contacts.h ---- */
#ifndef CONTACTS_H
#define CONTACTS_H

#include <stddef.h>

#define NAME_MAX_LEN 50
#define PHONE_MAX_LEN 20

typedef struct {
    char name[NAME_MAX_LEN];
    char phone[PHONE_MAX_LEN];
} Contact;

typedef struct {
    Contact *items;
    size_t count;
    size_t capacity;
} ContactList;

void contacts_init(ContactList *list);
void contacts_free(ContactList *list);
int contacts_add(ContactList *list, const char *name, const char *phone); /* 0 ok, -1 error */
int contacts_find(const ContactList *list, const char *name);             /* index or -1 */
int contacts_remove(ContactList *list, size_t index);                     /* 0 ok, -1 bad index */
int contacts_load(ContactList *list, const char *path);                   /* 0 ok, -1 error */
int contacts_save(const ContactList *list, const char *path);             /* 0 ok, -1 error */

#endif /* CONTACTS_H */

/* ---- contacts.c ---- */
#include "contacts.h"

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

void contacts_init(ContactList *list) {
    list->items = NULL;
    list->count = 0;
    list->capacity = 0;
}

void contacts_free(ContactList *list) {
    free(list->items);
    contacts_init(list);
}

int contacts_add(ContactList *list, const char *name, const char *phone) {
    if (name[0] == '\0' || strlen(name) >= NAME_MAX_LEN || strlen(phone) >= PHONE_MAX_LEN) {
        return -1;
    }
    if (strchr(name, ';') != NULL || strchr(phone, ';') != NULL) {
        return -1; /* ';' is the field separator in the file */
    }
    if (list->count == list->capacity) {
        size_t new_capacity = list->capacity == 0 ? 4 : list->capacity * 2;
        Contact *bigger = realloc(list->items, new_capacity * sizeof *bigger);
        if (bigger == NULL) {
            return -1; /* the old block is still valid and owned by the list */
        }
        list->items = bigger;
        list->capacity = new_capacity;
    }
    Contact *slot = &list->items[list->count];
    snprintf(slot->name, sizeof slot->name, "%s", name);
    snprintf(slot->phone, sizeof slot->phone, "%s", phone);
    list->count++;
    return 0;
}

int contacts_find(const ContactList *list, const char *name) {
    for (size_t i = 0; i < list->count; i++) {
        if (strcmp(list->items[i].name, name) == 0) {
            return (int)i;
        }
    }
    return -1;
}

int contacts_remove(ContactList *list, size_t index) {
    if (index >= list->count) {
        return -1;
    }
    memmove(&list->items[index], &list->items[index + 1],
            (list->count - index - 1) * sizeof(Contact));
    list->count--;
    return 0;
}

int contacts_load(ContactList *list, const char *path) {
    FILE *file = fopen(path, "r");
    if (file == NULL) {
        return errno == ENOENT ? 0 : -1; /* no file yet: start empty */
    }
    char line[NAME_MAX_LEN + PHONE_MAX_LEN + 8];
    char name[NAME_MAX_LEN];
    char phone[PHONE_MAX_LEN];
    while (fgets(line, sizeof line, file) != NULL) {
        line[strcspn(line, "\r\n")] = '\0';
        if (line[0] == '\0') {
            continue;
        }
        /* the widths 49 and 19 must match NAME_MAX_LEN - 1 and PHONE_MAX_LEN - 1 */
        if (sscanf(line, "%49[^;];%19s", name, phone) != 2) {
            fprintf(stderr, "skipping invalid line: %s\n", line);
            continue;
        }
        if (contacts_add(list, name, phone) != 0) {
            fclose(file);
            return -1;
        }
    }
    int failed = ferror(file);
    fclose(file);
    return failed ? -1 : 0;
}

int contacts_save(const ContactList *list, const char *path) {
    char tmp_path[256];
    if (snprintf(tmp_path, sizeof tmp_path, "%s.tmp", path) >= (int)sizeof tmp_path) {
        return -1;
    }
    FILE *file = fopen(tmp_path, "w");
    if (file == NULL) {
        return -1;
    }
    for (size_t i = 0; i < list->count; i++) {
        if (fprintf(file, "%s;%s\n", list->items[i].name, list->items[i].phone) < 0) {
            fclose(file);
            remove(tmp_path);
            return -1;
        }
    }
    if (fclose(file) != 0) {
        remove(tmp_path);
        return -1;
    }
#ifdef _WIN32
    remove(path); /* on Windows rename() does not replace an existing file */
#endif
    if (rename(tmp_path, path) != 0) {
        remove(tmp_path);
        return -1;
    }
    return 0;
}

The menu: what you must complete

In main.c we give you the skeleton with the read_line helper and options 1 (list) and 2 (add). You complete options 3 (search) and 4 (delete). The input buffers are bigger than the contact fields on purpose: that way, if the user types a 200-character name, fgets reads it all and contacts_add rejects it with a clear message, instead of leaving garbage unread on the input. When deleting, ask for the number shown by the listing (which starts at 1) and convert it with strtol, checking it is valid, before calling contacts_remove with index - 1.

c
/* ---- main.c ---- */
#include <stdio.h>
#include <string.h>

#include "contacts.h"

#define DATA_FILE "contacts.txt"
#define INPUT_SIZE 128

/* Prints the prompt and reads one line without the newline. Returns -1 on EOF. */
static int read_line(const char *prompt, char *buffer, size_t size) {
    printf("%s", prompt);
    if (fgets(buffer, (int)size, stdin) == NULL) {
        return -1;
    }
    buffer[strcspn(buffer, "\r\n")] = '\0';
    return 0;
}

static void list_all(const ContactList *list) {
    if (list->count == 0) {
        puts("(no contacts)");
        return;
    }
    for (size_t i = 0; i < list->count; i++) {
        printf("%zu. %s - %s\n", i + 1, list->items[i].name, list->items[i].phone);
    }
}

int main(void) {
    ContactList list;
    contacts_init(&list);
    if (contacts_load(&list, DATA_FILE) != 0) {
        fprintf(stderr, "cannot read %s\n", DATA_FILE);
        contacts_free(&list);
        return 1;
    }

    char choice[INPUT_SIZE];
    char name[INPUT_SIZE];
    char phone[INPUT_SIZE];

    for (;;) {
        puts("\n1) List  2) Add  3) Search  4) Delete  0) Save and exit");
        if (read_line("> ", choice, sizeof choice) != 0 || strcmp(choice, "0") == 0) {
            break;
        }
        if (strcmp(choice, "1") == 0) {
            list_all(&list);
        } else if (strcmp(choice, "2") == 0) {
            if (read_line("Name: ", name, sizeof name) != 0 ||
                read_line("Phone: ", phone, sizeof phone) != 0) {
                break;
            }
            if (contacts_add(&list, name, phone) != 0) {
                puts("Could not add: empty, too long or contains ';'.");
            } else {
                puts("Added.");
            }
        } else if (strcmp(choice, "3") == 0) {
            /* TODO: read a name, use contacts_find and print the contact or "Not found." */
            puts("Not implemented yet.");
        } else if (strcmp(choice, "4") == 0) {
            /* TODO: list_all, read a number, validate it with strtol, remove index - 1 */
            puts("Not implemented yet.");
        } else {
            puts("Unknown option.");
        }
    }

    int status = 0;
    if (contacts_save(&list, DATA_FILE) != 0) {
        fprintf(stderr, "could not save %s\n", DATA_FILE);
        status = 1;
    }
    contacts_free(&list);
    return status;
}
make
CC = gcc
CFLAGS = -std=c17 -Wall -Wextra -Wpedantic -g -MMD -MP
OBJS = main.o contacts.o

contacts: $(OBJS)
	$(CC) $(OBJS) -o contacts

%.o: %.c
	$(CC) $(CFLAGS) -c $< -o $@

-include $(OBJS:.o=.d)

.PHONY: run clean check
run: contacts
	./contacts

# build a copy with the sanitizers and run it to look for hidden bugs
check:
	$(CC) -std=c17 -g -fsanitize=address,undefined main.c contacts.c -o contacts_asan
	./contacts_asan

clean:
	rm -f $(OBJS) $(OBJS:.o=.d) contacts contacts_asan

Suggested steps and criteria

Work in stages: first write the header and the Makefile and check that it compiles empty; second, copy contacts.c and test options 1 and 2; third, check that exiting with 0 creates contacts.txt and that when you reopen the program the contacts reappear; fourth, implement 3 and 4; fifth, run make check and try to break it with absurd inputs: an empty name, a 300-character one, a name with ';', deleting number 0 or 99, closing input with Ctrl+D. Every failure you find is a new test that must pass. If ASan reports a leak, look for the path that leaves main without calling contacts_free.

  • make compiles with no warnings and make check produces no ASan or UBSan reports.
  • Adding, searching, deleting and listing work, including the error cases.
  • Contacts survive between runs and contacts.txt can be opened with an editor.
  • There are no leaks: every malloc/realloc has its free.
  • No user input can write outside a buffer.
  • You can explain why contacts_add does not assign realloc directly to list->items.

检验所学

第 1 / 8

Why is realloc not assigned directly to the original pointer?

✎ 我的笔记

仅保存在此浏览器中。登录后可保存到账号。0/5000 字符

← 上一节