1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177
|
/* http://delahaye.emmanuel.free.fr/clib/ */
#include "ed/inc/prt.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#define FNAME "carnet.agd"
typedef struct
{
char *nom;
char *prenom;
char *tel;
unsigned char age;
}
fiche;
typedef struct element
{
fiche *pfiche;
struct element *NextElem;
}
element;
typedef struct
{
element *PremElem;
element *DernElem;
}
fichier;
static char *str_dup (char const *s)
{
size_t size = strlen (s) + 1;
char *sdup = malloc (size);
if (sdup != NULL)
{
memcpy (sdup, s, size);
}
return sdup;
}
static void list_free (fichier * p_fic)
{
element *p = p_fic->PremElem;
while (p != NULL)
{
element *old = p;
p = p->NextElem;
{
fiche *f = old->pfiche;
if (f != NULL)
{
free (f->nom);
free (f->prenom);
free (f->tel);
free (f);
}
}
free (old);
}
}
static void Restaure (fichier * p_fic)
{
FILE *fd = fopen (FNAME, "r");
if (fd == NULL)
{
printf ("Erreur d'ouverture du fichier\n");
}
else
{
int err = 0;
char tamp[100];
/* lecture d'une ligne */
while (fgets (tamp, sizeof tamp, fd) != NULL)
{
element *NElem = malloc (sizeof *NElem);
err = NElem == NULL;
if (!err)
{
fiche *f = malloc (sizeof *f);
{
static const element z = { 0, NULL };
*NElem = z;
}
err = f == NULL;
if (!err)
{
static char const SEP[] = ";\n";
char *p = strtok (tamp, SEP);
{
static const fiche z = { NULL, NULL, NULL, 0 };
*f = z;
}
err = p == NULL;
if (!err)
{
f->nom = str_dup (p);
p = strtok (NULL, SEP);
err = p == NULL;
if (!err)
{
f->prenom = str_dup (p);
p = strtok (NULL, SEP);
err = p == NULL;
if (!err)
{
f->tel = str_dup (p);
p = strtok (NULL, SEP);
err = p == NULL;
if (!err)
{
f->age = strtol (p, NULL, 10);
NElem->pfiche = f;
if (p_fic->PremElem == NULL)
{
p_fic->PremElem = NElem;
}
else
{
p_fic->DernElem->NextElem = NElem;
}
p_fic->DernElem = NElem;
}
}
}
}
}
}
}
if (err)
{
list_free (p_fic);
}
fclose (fd);
}
}
int main (void)
{
fichier carnet = { NULL, NULL };
Restaure (&carnet);
/* affichage */
{
element const *p = carnet.PremElem;
while (p != NULL)
{
fiche const *const f = p->pfiche;
if (f != NULL)
{
PRT_S (f->nom);
PRT_S (f->prenom);
PRT_S (f->tel);
PRT_I (f->age);
printf ("\n");
}
p = p->NextElem;
}
}
/* liberation */
list_free (&carnet);
return 0;
} |
Partager