istream::read problem

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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
// Use random-access I/O to read specific inventory records 
// from a data file. This program reads the file InvDat.dat, 
// which is created by the example program in the recipe: 
//  
//   Write Unformatted Binary Data to a File 
 
#include <iostream> 
#include <fstream> 
#include <cstdlib> 
 
using namespace std; 
 
// A simple inventory structure. 
struct inventory { 
  char item[20]; 
  int quantity; 
  double cost; 
}; 
 
int main(int argc, char *argv[]) 
{ 
  inventory entry; 
  long record_num; 
 
  if(argc != 2) { 
    cout << "Usage: ShowRecord <record-num>\n"; 
    return 1; 
  } 
 
  // Convert the string representation of the entry 
  // number into a long value. 
  record_num = atol(argv[1]); 
 
  // Confirm that the record number is greater than or 
  // equal to zero. 
  if(record_num < 0) { 
    cout << "Record numbers must be greater than or equal to 0.\n"; 
    return 1; 
  } 
 
  // Open the file for binary input. 
  ifstream fInvDB("InvDat.dat", ios::in | ios::binary); 
 
  // Confirm that the file opened without error. 
  if(!fInvDB) { 
    cout << "Cannot open file.\n"; 
    return 1; 
  } 
 
  // Read and display the entry specified on the command line. 

 // First, seek to the desired record. 
 fInvDB.seekg(sizeof(inventory) * record_num, ios::beg); 
 // Next, read the record. 
 fInvDB.read((char *) &entry, sizeof(inventory)); 
 // Close the file. 
 fInvDB.close(); 
 // Confirm that there were no file errors. 
 if(!fInvDB.good()) { 
   cout << "A file error occurred.\n"; 
   return 1; 
 } 
 // Display the inventory for the specified entry. 
 cout << entry.item << endl; 
 cout << "Quantity on hand: " << entry.quantity; 
 cout << "\nCost: " << entry.cost << endl; 
 return 0; 
}


After going through data to set the pointer in the front of the requested record

fInvDB.seekg(sizeof(inventory) * record_num, ios::beg);

And start reading :

fInvDB.read((char *) &entry, sizeof(inventory));

How does it knows that &entry is referencing to an inventory (a structure) ? Because of the lines :

1
2
3
4
  // Display the inventory for the specified entry. 
  cout << entry.item << endl; 
  cout << "Quantity on hand: " << entry.quantity; 
  cout << "\nCost: " << entry.cost << endl; 


shows that the program knows entry is a structure,class of some sort.
Last edited on
It knows that entry is an inventory because of the line 22, where you told the compiler that entry is an inventory.
Topic archived. No new replies allowed.