Do you mean reading binary files directly into the structure?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
struct POD
{
int a;
float b;
float c;
};
POD data[ 10 ];
int num_elements;
ifstream file( "foo.dat", ios::binary );
file.read( const_cast<char*>( data ), sizeof( data ) );
if (!file)
num_elements = file.gcount() / sizeof( data[ 0 ] );
else
num_elements = sizeof( data ) / sizeof( data[ 0 ] );
file.close();
Or do you mean reading textual data?
In this case it depends entirely on how your data is written to file. The following example assumes that each structure just lists its contents one by one separated by some whitespace. For example:
10 9.2 7.3
99 -0.4 500.009
12 1.0 8.9
or
10
9.2
7.3
99
-0.4
500.009
12
1.0
8.9
or whatever, so long as everything is separated by whitespace
1 2 3 4 5 6 7 8 9 10 11 12 13 14
struct POD ...;
istream& operator >> (istream& ins, POD& datum)
{
ins >> datum.a >> datum.b >> datum.c;
return ins;
}
POD data[ 10 ];
int num_elements;
ifstream file( "foo.txt" );
for (num_elements = 0; num_elements < 10; num_elements++)
if (!(file >> data[ num_elements ])) break;
file.close();