简体   繁体   中英

Trying to read numbers from binary file ( fread,fwrite)

I'm trying to write numbers to a binary file and then read them back.

But when i enter more then 13 numbers program stucks and dont show me results.

here's my code :

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


int main()
{
FILE *fp;

int  a[100],
     b[100],
     i,n;

fp=fopen("temp.dat", "w+b");

printf("Enter N: \n");
scanf("%d",&n);

for(i=0;i<n;i++){
    printf("Enter (%d) number \n",i+1);
    scanf("%d",&a[i]);
}

    fwrite(a, sizeof(a), n , fp);
    rewind(fp);
    fread(b, sizeof(b), n , fp);


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


fclose(fp);
system("pause");
return 0;
}

This:

fread(b, sizeof(b), n , fp);

reads sizeof(b) * n bytes in b array but b has only sizeof b bytes.

You have a similar issue with your fwrite call.

I suggest you to read again the manual of fread and fwrite functions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM