There are two situations that need to pay attention to your code:
You are reading and writing the array multiple times in fors
:
for(i=0;i<3;i++)
{
...
fwrite(&num1[i],sizeof(num1[i]),100,fp); //<--
}
for(i=0;i<3;i++)
{
...
fread(&num1[i],sizeof(num1[i]),100,fp); //<--
}
It is important to remember that fwrite(&num1[i],sizeof(num1[i]),100,fp)
writes the whole array to the file, as the third parameter is the 100
is the amount of elements to write. This means you are typing 3
arrays for the file and then reads the 3 arrays of the same file. And these arrays have only a few values filled, getting the rest with what was in memory.
The solution is not to write and read to file inside the for
, or swap the array for loose variables and save/read one by one in the for
.
You are not closing the file you opened for writing so you can open it as a read. It will even work in some implementations but not in others. The correct thing is to close with fclose
and open again with fopen
, indicating a binary read mode as rb
.
Hitting these two problems your code gets like this:
int main() {
FILE *fp;
int i;
int num1[100];
fp=fopen("Teste.bin","wb+");
if(fp<0) {
printf("Erro ao abrir arquivo!!!\n");
}
for(i=0; i<3; i++) {
printf("Digite valor");
scanf("%d",&num1[i]);
}
fwrite(num1,sizeof(num1[0]),100,fp); //escreve uma vez
fclose(fp); //fecha
fp = fopen("Teste.bin","rb"); //abre para leitura
fread(num1,sizeof(num1[0]),100,fp); //le uma vez
for(i=0; i<3; i++) {
printf("\nNumero: %d",num1[i]);
}
fclose(fp);
return(0);
}
Note: Does not include file opening error test in the second fopen
for simplicity’s sake.
But what was your intention with this program ? Each
fwrite
which has writes the whole array– Isac
write 3 numbers and print them after something very simple
– FZero
But for that you don’t need the array. Writing based on the array only makes sense if you write the numbers all at once and only once, and to do so simply pull the
fwrite
andfread
out offor
. This is thefwrite
after the firstfor
and thefread
right after, before the lastfor
.– Isac
ah ta, I thought it was that neither txt file that had to use array for everything =)
– FZero