-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathfiles-1.cpp
More file actions
83 lines (63 loc) · 2.28 KB
/
files-1.cpp
File metadata and controls
83 lines (63 loc) · 2.28 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
81
82
#include <iostream>
#include <fstream>
#include <cassert>
#include <vector>
void textMode(const std::string& fileNameIn, const std::string& fileNameOut) {
/// Открыть файл для чтения
std::ifstream input(fileNameIn);
assert(input.is_open());
/// Считать как текстовый файл, преобразуя к int'ам
std::vector<int> data;
int i;
while (input >> i) {
data.push_back(i);
std::cout << "Read integer: " << i << std::endl;
}
/// Закрыть файл (input.good() == false, т.к. достигли конца файла)
assert(!input.bad());
input.close();
/// Открыть файл для записи
std::ofstream output;
output.open(fileNameOut, std::ios::out); // или std::ios::app -- дозаписать в конец
assert(output.is_open());
/// Записать информацию
for (int i : data) { output << i << " "; }
/// Закрыть файл
assert(output.good());
output.close();
}
void textModeGetline(const std::string& fileNameIn) {
/// Открыть файл для чтения
std::ifstream input(fileNameIn);
assert(input.is_open());
/// Считать одну строку
std::string s;
std::getline(input, s);
std::cout << "Read string \"" << s << "\"" << std::endl;
/// Закрыть файл (input.good() == false, т.к. достигли конца файла)
assert(!input.bad());
input.close();
}
void binaryMode(const std::string& fileName) {
std::ofstream output;
output.open(fileName, std::ios::binary);
assert(output.is_open());
std::vector<double> data = { 1, 2, 3 };
std::streamsize bufferSize = (std::streamsize)(data.size() * sizeof(double));
std::streamsize previousNumberOfBytes = output.tellp();
/// Записать как массив байт
assert(output.write(reinterpret_cast<const char*>(data.data()), bufferSize));
std::streamsize currentNumberOfBytes = output.tellp();
assert(bufferSize == currentNumberOfBytes - previousNumberOfBytes);
assert(output.good());
output.close();
}
int main() {
const std::string fileNameIn = "testIn.txt";
const std::string fileNameOut = "testOut.txt";
const std::string binFileName = "testBin.txt";
textMode(fileNameIn, fileNameOut);
textModeGetline(fileNameIn);
binaryMode(binFileName);
return 0;
}