Mary Poppins
Mary Poppins

Reputation: 79

Reading an array from a binary file in c returns incorrect values

I just started learning files in c language and i have a problem with my code. It works just fine writing in the binary file, but when im trying to read the values back, it returns one less value and also different values for the array. I am aware that probably i've made a dumb mistake, if you could help me understand i would be greatful. This is my code :

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()

{
    FILE *f;
    if ((f=fopen("fis.bin","wb"))==NULL)
    {
        printf ("Error\n");
        exit(1);
    }

    int *v;
    int n,x;
    char s[100];
    scanf("%d",&n);
    v=(int*)malloc(n*sizeof(int));

    for (int i=0; i<n; i++)
    {
        scanf("%d",&v[i]);

        x=fprintf(f,"%d\n",v[i]);
        if (x<0)
            perror("Error:");
    }
    fclose(f);

    int *cit;

    cit=(int*)calloc(n,sizeof(int));

    if ((f=fopen("fis.bin","rb"))==NULL)
    {
        printf ("Error\n");
        exit(1);
    }
    fseek(f,0,SEEK_END);

    int sz = ftell(f)/sizeof(v[0]);

    fseek(f,0,0);

    int i=0;

    if(!fread(cit,sizeof(int),sz,f))
        perror("err: ");

    for (i=0; i<sz; i++)
        printf("%d\n",cit[i]);



    printf("\n");

    free(v);
    free(cit);


    fclose(f);

}

Upvotes: 1

Views: 1555

Answers (1)

kiran Biradar
kiran Biradar

Reputation: 12732

The problem is you are writing to the file using fprintf.

where as fprintf writes string representation of integers. For example, when you write 2 to the file you are writing "2" as string of size 1 byte.

x=fprintf(f,"%d\n",v[i]);

Thus replace fprintf with fwrite as below.

fwrite(&v[i], sizeof(v[0]), 1, f);

fwrite writes binary representation of integer.

Upvotes: 1

Related Questions