Variable returning 0 to file

0
Hello, I'm learning files I'm having a hard time using fwrite and fread, then the variable num1 is returning me 0 in the repeat structure and I think I did everything right = (

#include<stdio.h>
#include<stdlib.h>


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[i],sizeof(num1[i]),100,fp);
 }
 for(i=0;i<3;i++)
 {
     fread(&num1[i],sizeof(num1[i]),100,fp);
     printf("\nNumero: %d",num1[i]);
 }

 fclose(fp);
 return(0);
}
    
asked by anonymous 15.06.2018 / 03:48

1 answer

0

There are two situations that you need to be aware of in 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 entire array to the file, because the third parameter that is 100 is the number of elements to write. This means that you are writing 3 arrays to the file and then reads the 3 arrays of the same file. And these arrays have only a few values filled in, leaving the rest with what was in memory.

    The solution is not to write and read to the file within for , or to change the array by loose variables and to write / read one by one in for .

  • You are not closing the file you opened for writing to be able to open as a read. This will even work in some implementations but not in others. The correct one is to close with fclose and reopen with fopen , indicating a binary read mode as rb .

By fixing these two problems your code looks 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: It does not include the file opening error test on the second fopen for simplicity itself.     

15.06.2018 / 04:13