This repository has been archived by the owner on Dec 31, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
files.cpp
104 lines (81 loc) · 2.42 KB
/
files.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
99
100
101
102
103
104
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
std::vector<uint8_t> ReadBytesFromFile(std::string filename, int n) {
static std::ifstream read_stream; //TODO: Close read stream
if (!read_stream.is_open()) {
read_stream.open(filename, std::ios_base::binary);
}
std::streampos starting_read_position = read_stream.tellg();
char* char_bytes = new char[n];
if (__CHAR_BIT__ / 8 == sizeof(uint8_t)) {
read_stream.readsome(char_bytes, n);
}
else {
std::cout << "ERROR: Incompatible machine.";
}
std::vector<uint8_t> bytes(char_bytes, char_bytes + read_stream.tellg() - starting_read_position);
delete(char_bytes);
if (bytes.size() < 512) {
read_stream.close();
}
return bytes;
}
void WriteBytesToFile(std::string filename, std::vector<uint8_t> bytes) {
static std::ofstream write_stream;
if (!write_stream.is_open()) {
write_stream.open(filename, std::ios_base::ate | std::ios_base::trunc | std::ios_base::binary);
}
write_stream.write(reinterpret_cast<char*>(bytes.data()), bytes.size());
if (bytes.size() < 512) {
write_stream.close();
}
}
void WriteNetASCIIToFile(std::string filename, std::vector<uint8_t> bytes) {
static std::ofstream write_stream;
if (!write_stream.is_open()) {
write_stream.open(filename, std::ios_base::ate | std::ios_base::trunc);
}
for (int i = 0; i < bytes.size(); i++) {
if (bytes[i] == 13) {
bytes.erase(bytes.begin() + i);
}
}
write_stream.write(reinterpret_cast<char*>(bytes.data()), bytes.size());
if (bytes.size() < 512) {
write_stream.close();
}
}
std::vector<uint8_t> ReadNetASCIIFromFile(std::string filename, int n) {
static std::ifstream read_stream;
if (!read_stream.is_open()) {
read_stream.open(filename);
}
std::streampos starting_read_position = read_stream.tellg();
char* char_bytes = new char[n];
if (__CHAR_BIT__ / 8 == sizeof(uint8_t)) {
read_stream.readsome(char_bytes, n);
}
else {
std::cout << "ERROR: Incompatible machine.";
}
std::vector<uint8_t> bytes(char_bytes, char_bytes + read_stream.tellg() - starting_read_position);
delete(char_bytes);
if (bytes.size() < 512) {
read_stream.close();
}
for (int i = 0; i < bytes.size(); i++) {
if (bytes[i] == 10) {
if (i == 0 || bytes[i - 1] != 13) {
bytes.insert(bytes.begin() + i, 13);
}
}
else if (bytes[i] == 13) {
if (i == bytes.size() - 1 || bytes[i + 1] != 10) {
bytes.insert(bytes.begin() + i + 1, 0);
}
}
}
return bytes;
}