Pour ma fonction de récupération pour ma version avec taille de chaîne variable voici comment je fais:
Est ce optimisable?
Code : Sélectionner tout - Visualiser dans une fenêtre à part
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 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; void Restaure(fichier *p_fic) { int i, nbpv; element *NElem; fiche *f; char tamp[100], c; FILE *fd = fopen(FNAME, "r"); if(fd == NULL) { printf("Erreur d'ouverture du fichier\n"); return; } i = 0; nbpv = 0; while((c = fgetc(fd)) != EOF) { switch(c) { case ';': tamp[i] = '\0'; nbpv++; switch(nbpv) { case 1: NElem = malloc(sizeof *NElem); if(NElem == NULL) { printf("Erreur d'allocation\n"); break; } NElem->NextElem = NULL; f = malloc(sizeof *f); if(f == NULL) { free(NElem); printf("Erreur d'allocation\n"); break; } f->nom = malloc((strlen(tamp)+1) * sizeof *f->nom); if(f->nom == NULL) { free(f); free(NElem); printf("Erreur d'allocation\n"); break; } strcpy(f->nom, tamp); break; case 2: f->prenom = malloc((strlen(tamp)+1) * sizeof *f->prenom); if(f->nom == NULL) { free(f->nom); free(f); free(NElem); printf("Erreur d'allocation\n"); break; } strcpy(f->prenom, tamp); break; case 3: f->tel = malloc((strlen(tamp)+1) * sizeof *f->tel); if(f->nom == NULL) { free(f->prenom); free(f->nom); free(f); free(NElem); printf("Erreur d'allocation\n"); break; } strcpy(f->tel, tamp); break; } i = 0; break; case '\n': tamp[i] = '\0'; f->age = atoi(tamp); NElem->pfiche = f; if(p_fic->PremElem == NULL) { p_fic->PremElem = NElem; p_fic->DernElem = NElem; } else { p_fic->DernElem->NextElem = NElem; p_fic->DernElem = NElem; } i = 0; nbpv = 0; break; default: tamp[i] = c; i++; break; } } fclose(fd); }
Merci
Partager