-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinaryIn++.cpp
More file actions
80 lines (70 loc) · 2.15 KB
/
binaryIn++.cpp
File metadata and controls
80 lines (70 loc) · 2.15 KB
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
69
70
71
72
73
74
75
76
77
78
79
80
/**
* Purpose: binary file input example
* Author: Emanuele Rizzolo
* Class: 3XIN
* Date: 2020/04/26
* Note:
*/
// directive for standard io functions
#include <iostream>
// directive for file io functions
#include <fstream>
using namespace std;
// planet definition and data
#include "planet.h"
#define DEBUG 0
void print(const char title[], const planet planets[], int numPlanets);
// main function
int main(int argc, char *argv[])
{
// filename
const char filename[] = "planets++.dat";
// open the file for input
// automatic open with explicit open mode in and binary
ifstream infile(filename, ios::in | ios::binary);
// check failure
if (infile)
{
// success
// I/O operation
// get file dimension
infile.seekg(0, ios::end); // position at end of file
size_t dim = infile.tellg(); // get absolute position, i.e. file length
size_t planetsFound = dim / sizeof(planet);
if (dim != planetsFound * sizeof(planet))
{
cout << "File size (" << dim << ") not a multiple of sizeof(planet) = " << sizeof(planet) << endl;
}
planet *pianeti = new planet[planetsFound]; // for reading
if (pianeti == nullptr)
{
cout << "Cannot allocate memory for " << planetsFound << " planets" << endl;
}
else
{
infile.seekg(0); // reposition at begin of file
infile.read((char *)pianeti, planetsFound * sizeof(planet));
size_t letti = infile.gcount() / sizeof(planet);
print("Pianeti letti:", pianeti, letti);
// free allocated memory
delete[] pianeti;
}
// close file
infile.close();
}
else
{
cout << "failed to open file " << filename << endl;
}
// successful termination
return 0;
}
void print(const char title[], const planet planets[], int numPlanets)
{
cout << title << endl;
for (int p = 0; p < numPlanets; p++)
{
cout << planets[p] << endl;
}
cout << endl;
}