Re: Reading Files

Myself (and others) are wondering how to write prgs that read and manipulate data in files w/ structures and arrays.

For example, I know if you're using ints and floats u'd use sum'n like this:

struct fstruct
{
int a;
float b;
float c;
}

cout << "Enter a file name: ";
getline(cin, file_name);
file.open(file_name.c_str());
while((inByte = myFile.get()) !=EOF)
myFile.clear();
myFile.close();

this doesn't compile, but I know it looks kinda like that. can sum1 help me w/ this?
Your example isn't quite clear.

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();


Hope this helps.
I'm actually not sure which, but this is really helpful
Topic archived. No new replies allowed.