La fonction fread()

Résolu/Fermé
yougi Messages postés 22 Date d'inscription vendredi 8 juin 2007 Statut Membre Dernière intervention 13 mars 2010 - 13 mars 2010 à 22:13
yougi Messages postés 22 Date d'inscription vendredi 8 juin 2007 Statut Membre Dernière intervention 13 mars 2010 - 13 mars 2010 à 22:59
Bonjour,

Brièvement, Pourquoi ce code marche pas !!


#include <stdio.h>



typedef struct{
char *name;
int energy;
}robot;

int main() {

robot *r = (robot *)malloc(sizeof(robot));
robot *t = (robot *)malloc(sizeof(robot));
FILE *fichier;
int i;

r->energy = 4;
r->name = NULL;


fichier=fopen("write.txt","w");
for(i = 0; i < 5; i++)
fwrite(r, sizeof(robot),1,fichier);

fclose(fichier);

fichier=fopen("write.txt","r");

while(!eof(fichier)){
fread(t,sizeof(robot),1,fichier);
printf("%d---%s",t->energy,t->name);
}

fclose(fichier);

system("PAUSE");
return 0;
}

1 réponse

yougi Messages postés 22 Date d'inscription vendredi 8 juin 2007 Statut Membre Dernière intervention 13 mars 2010 8
13 mars 2010 à 22:59
C'est résolu... , je vais vous partager la solution.

Il faut remplacer ces lignes :

while(!eof(fichier)){
fread(t,sizeof(robot),1,fichier);
printf("%d---%s",t->energy,t->name);
}

par ces nouvelles lignes :

while(fread(t,sizeof(robot),1,fichier) != 0)
printf("%d---%s",t->energy,t->name);

Pouquoi ?... Tout simplement car la détection de la fin du fichier se fait lorsque la fonction fread() retourne un zéro. ^^

Allez Merci comme même...
MEDIUMPP
2