This repository has been archived by the owner on Feb 28, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFileConverter.cpp
102 lines (81 loc) · 2.04 KB
/
FileConverter.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
#include "FileConverter.h"
bool FileConverter::IsTextFileValid(const std::string& filename)
{
auto input = std::ifstream(filename);
if (!input.is_open())
{
input.close();
throw std::runtime_error("Cannot open file! Is it used by another process?");
}
const auto records = std::count
(
std::istreambuf_iterator<char>(input),
std::istreambuf_iterator<char>(),
'\n'
);
input.close();
if (records % 2 == 1)
{
throw std::runtime_error("Text file has contains odd number of records.");
}
return true;
}
bool FileConverter::AreStreamsOpened(std::ifstream& input, std::ofstream& output)
{
if (!input.is_open() || !output.is_open())
{
output.close();
input.close();
throw std::runtime_error("Cannot open files! Are they used by another process?");
}
return true;
}
std::string FileConverter::TextToBinary(std::string filename) const
{
filename = this->directory + "/" + filename;
if (!IsTextFileValid(filename))
{
throw std::exception("Text file is not valid.");
}
auto inputName = filename + ".txt";
auto outputName = filename + ".bin";
auto input = std::ifstream(inputName, std::ofstream::binary);
auto output = std::ofstream(outputName);
if (!AreStreamsOpened(input, output))
{
throw std::exception("Cannot open IO streams.");
}
double number;
while (input >> number)
{
output.write(reinterpret_cast<char*>(&number), sizeof(double));
}
output.close();
input.close();
return outputName;
}
std::string FileConverter::BinaryToText(std::string filename) const
{
filename = this->directory + "/" + filename;
auto inputName = filename + ".bin";
auto outputName = filename + ".txt";
auto input = std::ifstream(inputName, std::ofstream::binary);
auto output = std::ofstream(outputName);
if (!AreStreamsOpened(input, output))
{
throw std::exception("Cannot open IO streams.");
}
double number;
while (input.good())
{
input.read(reinterpret_cast<char*>(&number), sizeof(double));
if (input.eof())
{
break;
}
output << number << std::endl;
}
output.close();
input.close();
return outputName;
}