Proyecto final: gestor de contactos en un archivo
Es la última lección y vas a usar casi todo lo que aprendiste: structs y typedef, memoria dinámica con malloc, realloc y free, cadenas seguras, funciones, varios archivos con headers, lectura y escritura de archivos, Makefile y herramientas de depuración. El proyecto es un gestor de contactos de consola: el programa carga una agenda desde un archivo de texto al arrancar, deja listar, añadir, buscar y borrar contactos desde un menú, y guarda los cambios al salir. Lo importante no es que sea grande, sino que sea correcto: sin fugas de memoria, sin desbordes y comprobando cada error.
Enunciado y requisitos
- Tres módulos: contacts.h/contacts.c (la lógica) y main.c (el menú), más un Makefile.
- Contact guarda name (máx. 49 caracteres) y phone (máx. 19) en arrays fijos.
- ContactList es un array dinámico que crece con realloc (capacidad inicial 4, se duplica).
- Funciones: añadir, buscar por nombre, borrar por índice, cargar y guardar. Cada una devuelve un código de error que main comprueba.
- Formato del archivo contacts.txt: una línea por contacto, nombre;teléfono.
- Si contacts.txt no existe al arrancar, la agenda empieza vacía; las líneas inválidas se saltan con un aviso en stderr.
- Menú: 1 listar, 2 añadir, 3 buscar, 4 borrar, 0 guardar y salir.
- Compila con -std=c17 -Wall -Wextra -Wpedantic sin avisos y pasa -fsanitize=address,undefined sin informes ni fugas.
El módulo de contactos
Empieza por el header: define las constantes de tamaño, los dos tipos y los prototipos con un comentario sobre qué devuelve cada función. Después implementa contacts.c. Fíjate en las decisiones de seguridad: contacts_add rechaza nombres vacíos, demasiado largos o con el separador ';', copia con snprintf, y solo modifica la lista si realloc tuvo éxito (nunca asignes el resultado de realloc directamente al puntero original, o perderás la memoria si falla). Te damos el módulo casi completo para que te concentres en main; léelo con cuidado antes de usarlo, porque debes poder explicar cada línea.
/* ---- 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;
}El menú: lo que tienes que completar
En main.c te damos el esqueleto con el ayudante read_line y las opciones 1 (listar) y 2 (añadir). Completa tú las opciones 3 (buscar) y 4 (borrar). Los buffers de entrada son más grandes que los campos del contacto a propósito: así, si el usuario escribe un nombre de 200 caracteres, fgets lo lee entero y contacts_add lo rechaza con un mensaje claro, en lugar de dejar basura sin leer en la entrada. Al borrar, pide el número que muestra el listado (que empieza en 1) y conviértelo con strtol, comprobando que sea válido, antes de llamar a contacts_remove con index - 1.
/* ---- 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;
}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_asanPasos sugeridos y criterios
Trabaja por etapas: primero escribe el header y el Makefile y comprueba que compila vacío; segundo, copia contacts.c y prueba las opciones 1 y 2; tercero, comprueba que al salir con 0 se crea contacts.txt y que al volver a abrir el programa los contactos reaparecen; cuarto, implementa 3 y 4; quinto, ejecuta make check y trata de romperlo con entradas absurdas: un nombre vacío, uno de 300 caracteres, un nombre con ';', borrar el número 0 o el 99, cerrar la entrada con Ctrl+D. Cada fallo que encuentres es una prueba nueva que debe pasar. Si ASan informa de una fuga, busca el camino que sale de main sin llamar a contacts_free.
- make compila sem avisos y make check no produce informes de ASan ni UBSan.
- Añadir, buscar, borrar y listar funcionan, incluidos los casos de error.
- Los contactos sobreviven entre ejecuciones y contacts.txt se puede abrir con un editor.
- No hay fugas: cada malloc/realloc tiene su free.
- Ninguna entrada del usuario puede escribir fuera de un buffer.
- Puedes explicar por qué contacts_add no asigna realloc directamente a list->items.
Pon a prueba lo aprendido
Pregunta 1 de 8¿Por qué no se asigna realloc directamente al puntero original?
✎ Mis apuntes
Guardado solo en este navegador. Inicia sesión para tenerlo en tu cuenta.0/5000 caracteres