cs_rt15
Messages postés
3874
Date d'inscription
mardi 8 mars 2005
Statut
Modérateur
Dernière intervention
7 novembre 2014
13
2 avril 2009 à 16:57
Tu écris sizeof(co1) = 4 octets.
Pourtant, tu fais un sprintf(co1,"%d",vecteur3[0]);
Donc si vecteur3[0] = 2, tu as "2\0XX" dans co1. C'est à dire 2, le zéro terminal, et deux caractères aléatoires.
Si tu écris ça dans le fichier, ça va effectivement faire un peu n'importe quoi.
Soit tu utilises strlen, soit tu termine co1 avec des espaces.
<hr />
#include <stdio.h>
#include <stdlib.h>
#include <string.h>int main()
{
float f1,f2,f3;
char co1[4];
char co2[4];
char co3[4];
int vecteur3[3];
FILE *fp;
vecteur3[0] = 1;
vecteur3[1] = 2;
vecteur3[2] = 3;
sprintf(co1,"%d",vecteur3[0]);
sprintf(co2,"%d",vecteur3[1]);
sprintf(co3,"%d",vecteur3[2]);
fp=fopen("vect3.txt","w+r");
fwrite (co1,strlen(co1),1,fp);
fwrite (" ",1,1,fp);
fwrite (co2,strlen(co2),1,fp);
fwrite (" ",1,1,fp);
fwrite (co3,strlen(co3),1,fp);
fseek(fp, SEEK_SET, 0);
fscanf(fp,"%f %f %f\n",&f1,&f2,&f3);
fclose(fp);
printf("%f et %f et %f\n",f1,f2,f3);
return 0;
}
<hr />#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void padd(char* lpStr, int nLen)
{
int i;
for (i = 0; i < nLen; i++)
if (! lpStr[i]) break;
for (;i < nLen; i++)
lpStr[i] = ' ';
}
int main()
{
float f1,f2,f3;
char co1[4];
char co2[4];
char co3[4];
int vecteur3[3];
FILE *fp;
vecteur3[0] = 1;
vecteur3[1] = 2;
vecteur3[2] = 3;
sprintf(co1,"%d",vecteur3[0]);
sprintf(co2,"%d",vecteur3[1]);
sprintf(co3,"%d",vecteur3[2]);
padd(co1, 4);
padd(co2, 4);
padd(co3, 4);
fp=fopen("vect3.txt","w+r");
fwrite (co1,sizeof(co1),1,fp);
fwrite (" ",1,1,fp);
fwrite (co2,sizeof(co2),1,fp);
fwrite (" ",1,1,fp);
fwrite (co3,sizeof(co3),1,fp);
fseek(fp, SEEK_SET, 0);
fscanf(fp,"%f %f %f\n",&f1,&f2,&f3);
fclose(fp);
printf("%f et %f et %f\n",f1,f2,f3);
return 0;
}