Reputation: 163
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;
}
Upvotes: 0
Views: 867
Reputation: 145829
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.
Upvotes: 2