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
|
#include <stdio.h>
#define NELEM(a) (sizeof(a)/sizeof*(a))
#define FNAME "c:\\exo1"
struct etudiants
{
unsigned matr;
char name[32];
};
/* ************************************************* */
static void charger_fichier (struct etudiants *tab, size_t n)
{
FILE *f = fopen (FNAME, "rb");
if (f != NULL)
{
size_t i;
int test;
printf ("AFFICHAGE DES ETUDIANTS (max %u)\n", (unsigned) n);
for (i = 0, test = -1; i < n && test != 0; i++)
{
struct etudiants *p = tab + i;
test = fread (p, sizeof *p, 1, f);
printf ("test=%d\n", test);
if (test != 0)
{
printf (" matricule %d\n", p->matr);
printf (" Mr/Mme %s\n\n", p->name);
}
}
fclose (f);
}
else
{
perror (FNAME);
}
}
/* ***************************************************************** */
static int save_bin (struct etudiants const *tab, size_t n)
{
FILE *f = fopen (FNAME, "wb");
if (f != NULL)
{
size_t i;
for (i = 0; i < n; i++)
{
fwrite (tab + i, sizeof *tab, 1, f);
}
fclose (f);
printf (" \nFichier sauvegarde.\n");
}
else
{
perror (FNAME);
}
return 0;
}
/* ***************************************************************** */
int main (void)
{
struct etudiants tab[] =
{
{123, "abc"},
{456, "def"},
#if 1
{78, "gh"},
#endif
};
#if 0
remove (FNAME);
save_bin (tab, NELEM (tab));
#else
charger_fichier (tab, NELEM (tab));
#endif
return 0;
} |
Partager