PDA

View Full Version : [C]Rubrica e liste concatenate ( linked lists )


kwb
14-09-2010, 10:12
Buongiorno a tutti!
Qua di nuovo per qualche problematica sul C... ( come sempre :asd: )
Avevo terminato di realizzare, qualche giorno fa, un programma in C che gestiva una semplice rubrica telefonica. Prendeva i nomi e i numeri da un file di testo e li sparava dentro un'array ( una struttura ), che conteneva altri due sottoarray: uno per il nome e l'altro per il numero.
Gli allocamenti di memoria erano contigui, quindi niente linked lists.

Ora è giunto il momento di fare lo stesso programma ma con le linked lists.
Sono riuscito a fare la parte della lettura del file ( che ovviamente non richeide l'utilizzo di liste ) e del contare quanti numeri ci sono...

Da questo punto in poi devo caricare i dati sulla mia variabile utilizzando le liste.

Ho problemi con lo fscanf, col quale non riesco a caricare i dati dentro la lista... Infatti mi ritorna come errore "EXC Bad Access"...

Questo è quanto ho scritto:

/*
Write a C program that manages a simple telephone directory. At startup, the program must read the directory from a file named “dir.txt”.
Each line in the file represents a directory entry and is composed of a telephone number (a sequence of characters without spaces of maximum
length 15) followed by a name (the rest of the line).

The following is a sample fragment of the file:
0115641234 Mario Rossi
+393396109876 John Smith
...

The program must store the directory in memory, and must work with names of maximum length defined by a constant.
The maximum number of entries in the telephone directory is unknown.
If the entries in the file exceed the available memory, the program must terminate with an error message.
After reading the file, the program must interact with the user by a menu with the following items:

L name looks for the specified name in the directory and prints the corresponding number.
A tel name adds a new tel-name entry to the in-memory directory (if space is available).
If an entry with the same name already exists, the telephone of that entry is updated.
D name deletes the entry with the given name in the in-memory directory (if present).
S saves the current in-memory directory to the file “dir.txt”.
Q quits the program.
*/

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

#define PHONEMAX 16 //15 +1 for '\0'
#define NAMEMAX 201 //200 +1 for '\0'
#define FILEMAX 31 //30 +1 for '\0'

typedef struct Data
{
char phone_number[PHONEMAX];
char name[NAMEMAX];
struct Data *next;
}data;


void emptyArray ( char *array );
void emptyBuffer (void);
int openFile ( FILE *fp, char *filename, int *fileLines);
data* getData ( FILE *fp, int fileLines, data *HEAD);

int main (void)
{
FILE *fp=NULL;
data *HEAD=NULL;
char filename[FILEMAX];
int fileLines=0;

emptyArray(filename);

printf("Insert the name of the file you want to open: ");
scanf("%30s", filename);
if ( (openFile(fp,filename,&fileLines))== -1)
{
printf("Error in opening the file\n");
return -1;
}
do
{
if ((HEAD=getData(fp, fileLines, HEAD))== NULL)
{
printf("Cannot allocate memory\n");
exit(1);
}
}while (HEAD -> next != NULL);



return 0;
}

void emptyArray ( char *array )
{
int i;
for ( i =0; i < FILEMAX; i++)
array[i] = '\0';
}

void emptyBuffer (void)
{
while (getchar()!='\n');
}

int openFile ( FILE *fp, char *filename, int *fileLines)
{
char line[PHONEMAX+NAMEMAX];

emptyArray(line);

if ((fp=fopen(filename, "r"))== NULL)
return -1;

while ((fgets(line, PHONEMAX+NAMEMAX, fp))!= NULL)
{
(*fileLines)++;
}
rewind(fp);

return 0;
}

data* getData ( FILE *fp, int fileLines, data *HEAD)
{
data *newNode;
int i;

for (i=0; i < fileLines; i++)
{
if ((newNode=(data*)malloc(sizeof(data)))==NULL)
{
printf("Malloc error\n");
exit(1);
}
fscanf(fp, "%s", newNode -> phone_number);
if((fseek(fp, PHONEMAX-strlen(newNode -> phone_number), SEEK_CUR))!=0)
{
printf("FSeek error\n");
exit(1);
}
fgets(newNode -> name, NAMEMAX-PHONEMAX+1, fp);
newNode -> next = HEAD;
}

return newNode;
}


Ho un dubbio sulla progettazione: conviene creare un'unica struttura che contiene la lista e i dati ( come ho fatto ) oppure due strutture, una per la lista e un'altra per i dati?

Sull'fscanf: obiettivamente non so se sia corretto scrivere quello che ho scritto...

Avendo avuto una spiegazione e degli esempi sommari da parte dei professori, mi risulta difficile comprendere appieno il funzionamento delle linked list. Ho bisogno di tanta pratica.
Inoltre i libri ( due ) utilizzano implementazioni differenti con spiegazioni non troppo chiare e quindi mi si incasina solo la vita :muro: .

Grazie anticipatamente

Kwb