Reading binary file

Hello I was given an assignment that was to open a binary file with records.
This is the the pseudocode

BEGIN main
Open the file
Call the displayLogFile_binary function
Close the file
End main
Create a global data structure to hold one data record
BEGIN displayLogFile_binary
Repeat until EOF:
Read one data record from file directly into the data structure
Print one line of the report (use the information just written to the data structure
end repeat
end displayLogFile_binary


I don't exactly know where to start in the displayLogFile_binary, but this is pretty much the skeleton that I have right now.
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
 #include <iostream>
#include <fstream>
using namespace std;

bool displayLogFile_binary(fstream &file);


struct WaterLog
{
	char name[15];
	char ID[8];
	int day, month, year;
	char sector;
	double firstM, secondM, thirdM;

};
int main()
{
	fstream file;

	file.open("Water_Log.dat",ios::in | ios::binary);

	if (file)
	{
		
		displayLogfile_binary(file);

		file.close();
	}
	else
	{
		cout << "Error opening file.";
	}
	return 0;


	system("pause");
	return 0;
}

bool displayLogFile_binary(fstream &file)
{

}
Last edited on
The Water_Log file contains this

day of month Integer 1 1-31
month Integer 1 1-12
year Integer 1 1900-3000
sector char 1 'N', 'S', 'E', 'W'
customer ID char 8 7 characters ending with a trailing 0
customer name char 15 14 characters ending with a trailing 0
gallons_1 double 1 number of gallons used in the 1st month
gallons_2 double 1 number of gallons used in the 2nd month
gallons_3 double 1 number of gallons used in the 3rd month

and this is the sample output

NAME ID DATE SECTOR MONTH_1 MONTH_2 MONTH_3 TOTAL AVERAGE
Baker 000-N01 05/28/2017 North 430.73 693.24 626.71 1750.68 583.56
Kimberly 387-W99 05/27/2017 East 822.42 98.55 60.68 981.65 327.22

So I know at some point, maybe when Inside the structure to find the average.
Last edited on
You could use use the read function of the fstream class.
1
2
3
4
5
6
7
8
9
10
11
12
bool displayLogFile_binary(fstream &file)
{
  if (!file)
    return false;

  WaterLog log = { 0 };
  while (file.read((char*)&log, sizeof(log)))
  {
    // TODO display the data
  }
  return true;
}

Topic archived. No new replies allowed.