I need to write function which will write elements of array into binary file, and after that find the mean value of elements of binary file.
#include <stdio.h>
double enterArray(){
int i=0,n;
double a[101];
FILE* fp=fopen("niz.bin", "w");
while(1){
scanf("%lf", &a[i]);
if(a[i]==-1)break;
i ;
if(i==100)break;
}
n=i;
for (i=0; i<n; i )
fwrite(a,4, n, fp);
fclose(fp);
return 0;
}
double meanValue(){
return 1;
}
int main() {
enterArray();
printf("%g\n", meanValue());
return 0;
}
I get some random characters in niz.bin file. Could you help me fix my code?
CodePudding user response:
There are a few problems with the code.
You take an arbitrary number of double
s, and then write the first n * 4 bytes in the array "repeatedly" to the file.
- You don't know for sure that
sizeof (double)
is equal to 4 bytes. - On every iteration, you write (n * 4) bytes from the array
a
to the file.- What you want is, starting from
i * sizeof (double)
, writesizeof (double)
bytes to the file (if you want to use a loop. You could simply just write (n * sizeof (double)
bytes to the file at once)
- What you want is, starting from
- You use the
"w"
mode infopen
, which is not the "write binary" mode. Use"wb"
instead.
Then, in meanValue()
, you don't do anything. Writing/reading a 10-element double
array to/from a binary file can be done in the following way:
/* write to the file */
double write_arr[10] = { 0.0, 1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9 };
FILE *fp = fopen("niz.bin", "wb");
fwrite(&write_arr, sizeof(double), 10, fp);
fclose(fp);
/* read from the file */
fp = fopen("niz.bin", "rb");
double read_arr[10];
fread(&read_arr, sizeof (double), 10, fp);
Also, note that you must identify how many elements you're going to write to the file, as you write the bytes in the file without knowing how many to write in advance. As you don't write the elements immediately, you could serialize the number of elements in the first 4 bytes in the file. And when you read from it, read the first 4 bytes to know how many double
s lying ahead.