High-Level and Low-Level I/O with classes

Hello,

I can overload << >> to work with classes.

But look at this :

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
#include <iostream> 
#include <fstream> 
#include <cstring> 
 
using namespace std; 
 
// A simple inventory structure. 
struct inventory { 
  char item[20]; 
  int quantity; 
  double cost; 
}; 
 
int main() 
{ 
  // Create and open a file for binary output. 
  ofstream fout("InvDat.dat", ios::out | ios::binary); 
 
  // Confirm that the file opened without error. 
  if(!fout) { 
    cout << "Cannot open file.\n"; 
    return 1; 
  } 
 
  // Create some inventory data. 
  inventory inv[3]; 
 
  strcpy(inv[0].item,"Hammers"); 
  inv[0].quantity = 3; 
  inv[0].cost = 9.99; 
 
  strcpy(inv[1].item, "Pliers"); 
  inv[1].quantity = 12; 
  inv[1].cost = 7.85; 
 
  strcpy(inv[2].item, "Wrenches"); 
  inv[2].quantity = 19; 
  inv[2].cost = 2.75; 
 
  // Write inventory data to the file. 
  for(int i=0; i<3; i++) 
    fout.write((const char *) &inv[i], sizeof(inventory)); 
 
  // Close the file. 
  fout.close(); 

  if(!fout.good()) { 
    cout << "A file error occurred."; 
    return 1; 
  } 
 
  return 0; 
}


But for low-level IO operations,using write or put functions.How the computer knows to write byte-to-byte to a file.

For the structure inventory written above, fout.write((const char *) &inv[i], sizeof(inventory)); what the cast did to it ?
The line you cited is badly written. If I understand it correctly, it is taking the address of each inventory and treating it as a cstring. This means that if the compiler decides to place either of the two numbers in inventory before the array in memory (which it is allowed to do), those numbers will be read as the first few characters. Also, you are always writing 20 characters even if you put fewer than 20 into the array, which might cause a bunch of garbage characters to be written.

If you use the << operator, your output is automatically formatted as readable text. The function write is used to write a block of unformatted data, so it saves whatever happens to be in inv[i], not necessarily readable text. If you open the folder for some random program and see lots of files you can't open like .dat, they were probably made with some variation of write; the format may only make sense to that one program.
Last edited on
Can I manually count the size of inventory ?

20 char = 20 bytes
1 int = 4 bytes
1 double = 8 bytes
===
Total : 32 bytes ?

After read 4 bytes for the int, 28 bytes remaining
After read 8 bytes for the double, 20 bytes remaining
After read 20 bytes for the array, 0 byte remaining.

So it always write 32 bytes,no matter the number of characters in the array is there ?
Topic archived. No new replies allowed.