Skip to content

Commit 1637a4c

Browse files
authored
Merge pull request #3 from m-axl/feature/first-phase
FEAT: implementar busca, remocao e persistencia da primeira fase
2 parents df83068 + e453d4e commit 1637a4c

6 files changed

Lines changed: 245 additions & 118 deletions

File tree

include/contact.h

Lines changed: 10 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,19 @@
11
#ifndef CONTACT_H
2-
#define CONTACT_H
2+
#define CONTACT_H
33

4-
#define MAX_NAME 100
5-
#define MAX_PHONE 20
4+
#define MAX_NAME 100
5+
#define MAX_PHONE 20
66

77
typedef struct {
8+
int id;
89
char name[MAX_NAME];
910
char phone[MAX_PHONE];
1011
} Contact;
1112

12-
void addContact(Contact contacts[], int *count); // Prototipo de função para adicionar um contato.
13-
void listContacts(Contact contacts[], int count); // Prototipo de função para listar os contatos.
14-
void removeContact(Contact contacts[], int *count); // Prototipo de função para remover um contato.
15-
int findContact(Contact contacts[], int id); // Prototipo de função para buscar um contato por ID.
13+
void addContact(Contact contacts[], int *count);
14+
void listContacts(Contact contacts[], int count);
15+
void searchContacts(Contact contacts[], int count);
16+
int findContact(Contact contacts[], int count, const char *query);
17+
void removeContact(Contact contacts[], int *count);
1618

17-
18-
#endif
19-
// Prototipo de função para buscar um contatos por nome.
20-
// Podde ser melhorada para retornar um ponteiro para o contato encontrado ou NULL se não encontrado.
19+
#endif

include/storage.h

Lines changed: 5 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,9 @@
1-
#ifndef STORAGE_H
2-
#define STORAGE_H
1+
#ifndef STORAGE_H
2+
#define STORAGE_H
33

44
#include "contact.h"
55

6-
// Prototipo de função para salvar os contatos em um arquivo.
7-
void saveContacts(
8-
Contact contacts[],
9-
int count
10-
);
6+
void saveContacts(Contact contacts[], int count);
7+
void loadContacts(Contact contacts[], int *count);
118

12-
// Prototipo de função para carregar os contatos do arquivo.
13-
void loadContacts(
14-
Contact contacts[],
15-
int *count
16-
);
17-
18-
// Prototipo de função para remover um contato do arquivo.
19-
20-
// Prototipo de função para buscar um contato por nome no arquivo.
21-
22-
// As funções removeContact e findContact ainda precisam ser implementadas, mas os protótipos já estão definidos para futuras implementações.
23-
24-
#endif
9+
#endif

src/contact.c

Lines changed: 132 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,31 +1,148 @@
1-
#include <stdio.h>
21
#include "../include/contact.h"
2+
#include <stdio.h>
3+
#include <stdlib.h>
4+
#include <string.h>
35

4-
// Função para adicionar um novo contato à lista.
5-
void addContact(Contact contacts[], int *count) {
6-
printf("Inserir nome do contato: \n");
7-
scanf("%99s", contacts[*count].name);
6+
void addContact(Contact contacts[], int *count)
7+
{
8+
printf("\n=== NOVO CONTATO ===\n");
9+
printf("Nome: ");
10+
fgets(contacts[*count].name, MAX_NAME, stdin);
11+
contacts[*count].name[strcspn(contacts[*count].name, "\n")] = '\0';
12+
printf("Telefone: ");
13+
fgets(contacts[*count].phone, MAX_PHONE, stdin);
14+
contacts[*count].phone[strcspn(contacts[*count].phone, "\n")] = '\0';
15+
contacts[*count].id = *count + 1;
16+
(*count)++;
17+
printf("\nContato adicionado.\n");
18+
}
819

9-
printf("Inserir telefone do contato: \n");
10-
scanf("%19s", contacts[*count].phone);
20+
void listContacts(Contact contacts[], int count)
21+
{
22+
int i;
1123

12-
(*count)++;
24+
if (count == 0) {
25+
printf("\nNenhum contato.\n");
26+
return;
27+
}
28+
29+
printf("\n=== CONTATOS ===\n");
30+
31+
for (i = 0; i < count; i++) {
32+
printf("\n[%d]\nNome: %s\nTelefone: %s\n",
33+
contacts[i].id,
34+
contacts[i].name,
35+
contacts[i].phone);
36+
}
1337
}
1438

15-
// Funçao para listar os contatos armazenados.
16-
void listContacts(Contact contacts[], int count) {
39+
void searchContacts(Contact contacts[], int count)
40+
{
41+
int i;
42+
int found = 0;
43+
char term[MAX_NAME];
44+
1745
if (count == 0) {
18-
printf("Nenhum contato encontrado!\n");
46+
printf("\nNenhum contato.\n");
47+
return;
48+
}
49+
50+
printf("\nTermo de busca: ");
51+
fgets(term, MAX_NAME, stdin);
52+
term[strcspn(term, "\n")] = '\0';
53+
54+
if (term[0] == '\0') {
55+
printf("\nTermo vazio. Digite um nome ou telefone.\n");
1956
return;
2057
}
2158

22-
for (int i = 0; i < count; i++) {
23-
printf("Contato %d:\n", i + 1);
24-
printf("Nome: %s | Telefone: %s\n", contacts[i].name, contacts[i].phone);
59+
printf("\n=== RESULTADO DA BUSCA ===\n");
60+
for (i = 0; i < count; i++) {
61+
if (strstr(contacts[i].name, term) != NULL ||
62+
strstr(contacts[i].phone, term) != NULL) {
63+
printf("\n[%d]\nNome: %s\nTelefone: %s\n",
64+
contacts[i].id,
65+
contacts[i].name,
66+
contacts[i].phone);
67+
found = 1;
68+
}
2569
}
70+
71+
if (!found)
72+
printf("\nNenhum contato encontrado para '%s'.\n", term);
2673
}
27-
// As funções removeContact e findContact ainda precisam ser implementadas.
2874

75+
int findContact(Contact contacts[], int count, const char *query)
76+
{
77+
int i;
78+
char *endptr;
79+
long id;
2980

81+
for (i = 0; i < count; i++) {
82+
if (strcmp(contacts[i].name, query) == 0 ||
83+
strcmp(contacts[i].phone, query) == 0)
84+
return i;
85+
}
3086

87+
id = strtol(query, &endptr, 10);
88+
if (*query != '\0' && *endptr == '\0') {
89+
for (i = 0; i < count; i++) {
90+
if (contacts[i].id == id)
91+
return i;
92+
}
93+
}
3194

95+
return -1;
96+
}
97+
98+
void removeContact(Contact contacts[], int *count)
99+
{
100+
int i;
101+
int index;
102+
char term[MAX_NAME];
103+
int confirm;
104+
int c;
105+
106+
if (*count == 0) {
107+
printf("\nLista vazia.\n");
108+
return;
109+
}
110+
111+
printf("\nNome, telefone ou ID do contato: ");
112+
fgets(term, MAX_NAME, stdin);
113+
term[strcspn(term, "\n")] = '\0';
114+
115+
if (term[0] == '\0') {
116+
printf("\nTermo vazio. Nenhum contato removido.\n");
117+
return;
118+
}
119+
120+
index = findContact(contacts, *count, term);
121+
if (index == -1) {
122+
printf("\nContato nao encontrado.\n");
123+
return;
124+
}
125+
126+
printf("\nContato encontrado:\n[%d] %s | %s\n",
127+
contacts[index].id,
128+
contacts[index].name,
129+
contacts[index].phone);
130+
printf("Confirmar remocao? (s/N): ");
131+
confirm = getchar();
132+
while ((c = getchar()) != '\n' && c != EOF)
133+
;
134+
if (confirm != 's' && confirm != 'S') {
135+
printf("\nRemocao cancelada.\n");
136+
return;
137+
}
138+
139+
for (i = index; i < *count - 1; i++)
140+
contacts[i] = contacts[i + 1];
141+
142+
(*count)--;
143+
144+
for (i = 0; i < *count; i++)
145+
contacts[i].id = i + 1;
146+
147+
printf("\nContato removido.\n");
148+
}

src/main.c

Lines changed: 51 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -7,46 +7,55 @@
77
#define MAX_CONTACTS 100
88

99
int main(void) {
10-
Contact contacts[MAX_CONTACTS];
11-
int count = 0;
12-
int option;
13-
14-
// Carregar contatos do arquivo ao iniciar o programa.
15-
loadContacts(contacts, &count);
16-
17-
do {
18-
printf("\nContact Manager\n");
19-
printf("1. Adicionar contato\n");
20-
printf("2. Listar contatos\n");
21-
printf("3. Sair\n");
22-
printf("Escolha uma opção: ");
23-
if (scanf("%d", &option) != 1) {
24-
fprintf(stderr, "Entrada inválida. Saindo.\n");
25-
break;
26-
}
27-
// Limpar o buffer de entrada para evitar problemas com scanf.
28-
switch (option) {
29-
case 1:
30-
if (count >= MAX_CONTACTS) {
31-
printf("Limite de contatos atingido.\n");
32-
} else {
33-
addContact(contacts, &count);
34-
}
35-
break;
36-
case 2:
37-
listContacts(contacts, count);
38-
break;
39-
case 3:
40-
saveContacts(contacts, count);
41-
printf("Contatos salvos. Até logo!\n");
42-
break;
43-
default:
44-
printf("Opção inválida. Tente novamente.\n");
45-
break;
46-
}
47-
} while (option != 3);
48-
49-
return 0;
10+
Contact contacts[MAX_CONTACTS];
11+
int count = 0;
12+
int option;
13+
int c;
14+
15+
loadContacts(contacts, &count);
16+
17+
do {
18+
printf("\n===Contact Manager===\n");
19+
printf("1. Adicionar contato\n");
20+
printf("2. Listar contatos\n");
21+
printf("3. Buscar contato\n");
22+
printf("4. Remover contato\n");
23+
printf("5. Sair\n");
24+
printf("Escolha uma opção: \n");
25+
26+
if (scanf("%d", &option) != 1) {
27+
fprintf(stderr, "Entrada inválida. Saindo.\n");
28+
break;
29+
}
30+
31+
while ((c = getchar()) != '\n' && c != EOF)
32+
;
33+
34+
switch (option) {
35+
case 1:
36+
if (count >= MAX_CONTACTS)
37+
printf("Limite de contatos atingido.\n");
38+
else
39+
addContact(contacts, &count);
40+
break;
41+
case 2:
42+
listContacts(contacts, count);
43+
break;
44+
case 3:
45+
searchContacts(contacts, count);
46+
break;
47+
case 4:
48+
removeContact(contacts, &count);
49+
break;
50+
case 5:
51+
saveContacts(contacts, count);
52+
printf("Contatos salvos. Até logo!\n");
53+
break;
54+
default:
55+
printf("Opção inválida. Tente novamente.\n");
56+
break;
57+
}
58+
} while (option != 5);
59+
60+
return 0;
5061
}
51-
// O programa agora inclui a funcionalidade de carregar e salvar contatos usando as funções definidas em storage.c.
52-
// As funções removeContact e findContact ainda precisam ser implementadas, mas a estrutura básica do programa já está funcional para adicionar e listar contatos.

src/storage.c

Lines changed: 31 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -1,40 +1,41 @@
1+
#include "../include/storage.h"
2+
#include <errno.h>
13
#include <stdio.h>
24
#include <sys/stat.h>
3-
#include <errno.h>
4-
#include "../include/storage.h"
55

6-
// Função para salvar os contatos em um arquivo.
76
void saveContacts(Contact contacts[], int count) {
8-
if (mkdir("data", 0755) != 0 && errno != EEXIST) {
9-
perror("Não foi possível criar diretório data\n");
10-
return;
11-
}
12-
13-
FILE *file = fopen("data/contacts.txt", "w");
14-
if (!file) {
15-
perror("Não foi possível abrir o arquivo de contatos\n");
16-
return;
17-
}
18-
19-
for (int i = 0; i < count; i++) {
20-
fprintf(file, "%s,%s\n", contacts[i].name, contacts[i].phone);
21-
}
22-
23-
fclose(file);
7+
int i;
8+
FILE *file;
9+
10+
if (mkdir("data", 0755) != 0 && errno != EEXIST) {
11+
perror("Não foi possível criar diretório data");
12+
return;
13+
}
14+
15+
file = fopen("data/contacts.txt", "w");
16+
if (!file) {
17+
perror("Não foi possível abrir o arquivo de contatos");
18+
return;
19+
}
20+
21+
for (i = 0; i < count; i++)
22+
fprintf(file, "%s,%s\n", contacts[i].name, contacts[i].phone);
23+
24+
fclose(file);
2425
}
2526

26-
// A função saveContacts agora inclui a criação do diretório "data" se ele não existir, garantindo que o arquivo de contatos possa ser salvo corretamente.
2727
void loadContacts(Contact contacts[], int *count) {
28-
FILE *f = fopen("data/contacts.txt", "r");
29-
if (!f) {
30-
return;
31-
}
28+
FILE *f;
29+
30+
f = fopen("data/contacts.txt", "r");
31+
if (!f)
32+
return;
3233

33-
while (fscanf(f, "%99[^,],%19[^\n]\n", contacts[*count].name, contacts[*count].phone) == 2) {
34-
(*count)++;
35-
}
34+
while (fscanf(f, "%99[^,],%19[^\n]\n", contacts[*count].name,
35+
contacts[*count].phone) == 2) {
36+
contacts[*count].id = *count + 1;
37+
(*count)++;
38+
}
3639

37-
fclose(f);
40+
fclose(f);
3841
}
39-
// A função loadContacts lê os contatos do arquivo "data/contacts.txt" e os armazena na matriz de contatos, atualizando o contador de contatos. Se o arquivo não existir, a função simplesmente retorna sem fazer nada, permitindo que o programa continue funcionando normalmente.
40-
// As funções saveContacts e loadContacts agora estão implementadas, permitindo que os contatos sejam salvos e carregados de um arquivo, garantindo a persistência dos dados entre as execuções do programa.

0 commit comments

Comments
 (0)