binary file read and struct

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>	
#include <fstream>	
using namespace std;	

struct details	{		
     char name[120];		
       int age;	
            };	

int main()	
{
			
details x;		
ifstream ins(“struct.dat”, ios::in | ios::binary);	
if (ins.good())		
{			
         while(!ins.eof())		
	          {ins.read((char*)&x, sizeof(details));			
	           cout << x.name << endl;			
	           cout << x.age << endl;			
         }
ins.close();		
}	
	return 0;	}


I do not understand how size of details make you output name and age? What if size of reads both name and age together and outputs both in x.name? I am confused how it is making x.name and x.age output?
I do not understand how size of details make you output name and age?

It doesn't output it, sizeof() returns the size of an object in bytes, in my machine, sizeof(details) returns 124, it is then passed as the second argument of istream::read() which make it extract 124 byes from the file
Last edited on
"Which make it extract 124 bytes from the file"

What if this 124 bytes include both name and age ? How does it differentiate between name and age? Sorry if I sound stupid...This is first time we are learning this in class
Last edited on
It doesn't; It takes your word and loads it in as it is represented in the struct.
Last edited on
so that is done by the compiler ?

Also what is this

istream& read(char* buf, streampos size);

what is istream& ? I never encountered a function return type with ampersand.

Thanks
Topic archived. No new replies allowed.