Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Reading Structure

Status
Not open for further replies.

RamHardikar

Programmer
Feb 16, 2001
109
GB
Hi,

I have a structure 'Employee' with attributes Name, Age and Salary. I am writing this structure for each employee in a file in binary mode. Also i am able to read structure 'Employee' from the file and display the values of Name, Age and Salary.

My question is can i read individual attributes of the structure (Name, Age and Salary)from the file without using structure? Could anyone help?


 
It depends on a structure alignment used by your compiler and is not (in general case) portable operation.
When your program writes a structure in a binary mode with sizeof(structure_type_or_variable), it writes padding bytes too. When you read back (with the same compiler on the same computer architecture), the structure contents is intact (real data in real data, gaps in gaps). To read a member you must know where (and how many) are alignment padding (garbage) bytes...
Of course, you may calculate real offsets of every member (via pointer arithmetics), but it's a rather cumbersom mechanics.
So it seems the only portable way: read a structure in a structure or use text mode data serialization...
 
You could, as ArkM already mentioned.
But you're not going to save a great deal in doing it.

Your disk allocation units are likely to be much larger than a single record, and that's the basic level of operation at the disk level - transferring allocation units to/from disk.

Your whole structure is already in memory, so whether fread() ends up memcpy'ing the whole record or just a field is neither here nor there.


--
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top