-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path06-file-handling.cpp
98 lines (76 loc) · 2.25 KB
/
06-file-handling.cpp
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
// can ignore this for now ------
// #if defined(_WIN32)
// #define SEP "\\"
// #else
// #define SEP "/"
// #endif
// ------------------------------
void output_matrix(int a[][3], int rows, int cols){
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
cout << a[i][j] << " ";
}
cout << endl;
}
}
void bin_example() {
int pixels[3][3];
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
pixels[i][j] = 1 + i*j;
output_matrix(pixels, 3, 3);
// writing to a file
ofstream fout("data.txt", ios::binary);
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
fout.write((char *)&pixels[i][j], sizeof(int) );
fout.close(); // notice what happens when we miss this
// read data back in
cout << "Resetting pixels ... " << endl;
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
pixels[i][j] = 0;
output_matrix(pixels, 3, 3);
cout << "Reading again ... " << endl;
ifstream fin("data.txt", ios::binary); // try missing file
// also try !fin in the condition
if(fin.fail()) {
cout << "Failed to read file ... " << endl;
} else {
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
fin.read((char *)&pixels[i][j], sizeof(int));
}
fin.close();
output_matrix(pixels, 3, 3);
}
/*
void char_example() {
// output file stream instance
ofstream fout;
string filename = "sample.txt"; // also try relative path
string line = "My test line ... ";
fout.open(filename); // default is ios::out, try ios::app
fout << line << endl; // as simple as that!
fout.close(); // need to remember this!
// input file stream instnace
ifstream fin;
fin.open(filename);
while (fin) {
getline(fin, line);
cout << line << endl;
}
fin.close();
} */
int main()
{
cout << "int: " << sizeof(int) << endl;
cout << "char: " << sizeof(char) << endl;
// char_example();
bin_example();
return 0;
}