I wrote some code which simply writes an array of doubles to a binary file
#include<stdio.h>
void main(void) {
// Open binary files
FILE *pFileResultsBin1;
FILE *pFileResultsBin2;
pFileResultsBin1 = fopen("results1.bin","wb+");
pFileResultsBin2 = fopen("results2.bin","wb+");
// Create array
double arr[3];
arr[0] = 1.0;
arr[1] = 2.0;
arr[2] = 3.0;
// Write array to binary files 10 times
int i;
// Method using sizeof(arr)
for(i=0;i<10;i++){
fwrite(&arr, sizeof(arr),1,pFileResultsBin1)
}
// Method using sizeof(arr[0])
for(i=0;i<10;i++){
fwrite(&arr, sizeof(arr[0]),3,pFileResultsBin2)
}
// Close files
fclose(pFileResultsBin1);
fclose(pFileResultsBin2);
}
When reading examples on the internet for writing arrays usually the method of sizeof(arr[0])
is used, but is there any disadvantage in using sizeof(arr)
? I tried both methods and both were read correctly using MATLAB:
FID1 = fopen(result1.bin);
FID2 = fopen(result1.bin);
A = fread(FID1,[3 inf],'*double','ieee-le');
B = fread(FID2,[3 inf],'*double','ieee-le');
Kind regards,
EJG
PS. I did not try to compile this specific example since I'm on a computer without compiler.
Have a look at the man-page http://www.freebsd.org/cgi/man.cgi?query=fwrite&apropos=0&sektion=0&manpath=FreeBSD+10.0-RELEASE&arch=default&format=html.
The return value of fwrite is the number of objects written. Hence, the first fwrite in your code will return 1 and the second 3, if the write is successful.
Besides that the calls are equivalent.