Questions about Files?

fread, fscanf and size of struct

fread, fscanf and size of struct

par weam haleemi,
Nombre de réponses : 3
Avatar GroupEn

doctor in the points2d and 3d exercise we needed to scan a struct of 3 points each of type double from the binary file.. can we use fread(array, sizeof(struct), 1, f)

or is it since the size of struct different than the total size of the 3 double numbers that we cannot use such syntax? although in the exercise session we used sizeof(student) in one of the exercises

En réponse à weam haleemi

Re: fread, fscanf and size of struct

par Siba Haidar,

Yes sure

The binary file contains point3d values, so you must read point3d using fread and you must not read 3 doubles because you know the binary representation of point3d may be different (slightlybigger dependingon the platform).

So you read a point3d one at a time and then you decide what to do with the value of each of its fields ... copy some, disregard others... 

En réponse à Siba Haidar

Re: fread, fscanf and size of struct

par weam haleemi,
Avatar GroupEn
doctor i used 3 scans of size double and i got accepted.. is it because of suitable testcases or are there exceptions
En réponse à weam haleemi

Re: fread, fscanf and size of struct

par Siba Haidar,
You got lucky by chance.
We discussed luck before.
The manual correction will remove the points because
In general
sizeof(point3d) >= 3* sizeof(double)

And not strictly =

So on a different platform successive reading of this form may fail to read the written data as it was.