Config.h - конфиг программы, где можно указать локаль программы - RU или EN, файл-источник, файл-результат, текст для перестановки.
Translator - переводчик, где указываются строки переводов для RU и EN локалей.
Класс FileManager - менеджер работы с файлами
Класс ConsoleLogger - простой логгер для консоли
Класс LinesProcessor - обработчик строк в файле. Внутри него как раз происходят перестановки строк.
Текст взял от юзера выше, спасибо ему!) Royal_X
main.cpp
| C++ | 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
| #include "Config.h"
#include "FileManager.h"
#include "ConsoleLogger.h"
#include "LinesProcessor.h"
std::unique_ptr<ConsoleLogger> initializeLogger();
std::unique_ptr<FileManager> initializeFileManager(const std::unique_ptr<ConsoleLogger>& logger);
std::unique_ptr<LinesProcessor> initializeLinesProcessor(const std::unique_ptr<ConsoleLogger>& logger, const std::unique_ptr<FileManager>& fm);
int main()
{
auto logger = initializeLogger();
auto fileManager = initializeFileManager(logger);
auto linesProcessor = initializeLinesProcessor(logger, fileManager);
auto lines = fileManager->GetFileContent(FILE_FOR_PROCCESS);
linesProcessor->Go(lines);
fileManager->WriteContentToFile(lines, PROCESSED_FILE);
return 0;
}
std::unique_ptr<ConsoleLogger> initializeLogger()
{
std::vector<LoggerParam> loggerConfig = { };
if (SYSTEM_LOCALE == RUSSIAN_LOCALE) {
loggerConfig.push_back(LoggerParam::ENABLE_RUSSIAN_LANGUAGE);
}
std::unique_ptr<ConsoleLogger> logger = std::make_unique<ConsoleLogger>(loggerConfig);
if (DEBUG_MODE) {
logger->PrintMessage("logger_initialized", { PrintMsgParam::SPECIAL_MESSAGE });
}
return logger;
}
std::unique_ptr<FileManager> initializeFileManager(const std::unique_ptr<ConsoleLogger>& logger)
{
std::unique_ptr fManager = std::make_unique<FileManager>(logger.get());
if (DEBUG_MODE) {
logger->PrintMessage("file_manager_initialized", { PrintMsgParam::SPECIAL_MESSAGE });
}
return fManager;
}
std::unique_ptr<LinesProcessor> initializeLinesProcessor(const std::unique_ptr<ConsoleLogger>& logger, const std::unique_ptr<FileManager>& fm)
{
std::unique_ptr linesProcessor = std::make_unique<LinesProcessor>(logger.get());
linesProcessor->SetFileManager(fm.get());
if (DEBUG_MODE) {
logger->PrintMessage("lines_processor_initialized", { PrintMsgParam::SPECIAL_MESSAGE });
}
return linesProcessor;
} |
|
FileManager.h
| C++ | 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
| #pragma once
#include "Config.h"
#include <iostream>
#include <vector>
#include "ConsoleLogger.h"
class FileManager
{
public:
FileManager();
FileManager(ConsoleLogger* logger);
~FileManager();
public:
bool AssertFileExists(const std::string& filename, const bool& loggerAlarmRequired = false);
bool IsFileEmpty(const std::string& filename, const bool& loggerAlarmRequired = false);
std::vector<std::string> GetFileContent(const std::string& filename);
void WriteContentToFile(std::vector<std::string>& lines, const std::string& filename);
private:
ConsoleLogger* logger;
}; |
|
FileManager.cpp
| C++ | 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
| #include "FileManager.h"
#include <fstream>
#include <filesystem>
#include <sstream>
#include <string>
typedef ConsoleLogger::PrintMessageParams PrintMsgParam;
FileManager::FileManager()
{ }
FileManager::FileManager(ConsoleLogger* logger)
: logger(logger)
{ }
FileManager::~FileManager()
{ }
bool FileManager::AssertFileExists(const std::string& filename, const bool& loggerAlarmRequired)
{
std::ifstream file(filename.c_str());
bool fileExists = file.good();
if (loggerAlarmRequired && logger) {
logger->PrintMessage("[" + filename + "] - ", { PrintMsgParam::SPECIAL_MESSAGE, PrintMsgParam::REMOVE_LINE_BREAK, PrintMsgParam::DONT_USE_TRANSLATOR });
if (fileExists) {
logger->PrintMessage("file_exists");
} else {
logger->PrintMessage("file_not_exists");
}
}
file.close();
return fileExists;
}
bool FileManager::IsFileEmpty(const std::string& filename, const bool& loggerAlarmRequired)
{
if (!this->AssertFileExists(filename, loggerAlarmRequired)) {
return true;
}
return this->GetFileContent(filename).empty();
}
std::vector<std::string> FileManager::GetFileContent(const std::string& filename)
{
std::vector<std::string> readingResult;
if (!this->AssertFileExists(filename, true)) {
return readingResult;
}
std::ifstream file(filename);
std::string line;
while (std::getline(file, line)) {
readingResult.push_back(line);
}
file.close();
return readingResult;
}
void FileManager::WriteContentToFile(std::vector<std::string>& lines, const std::string& filename)
{
std::ofstream file(filename, std::fstream::out);
for (std::string& line : lines) {
file << line << "\n";
}
this->logger->PrintMessage("new_data_writed_to_file", { PrintMsgParam::SPECIAL_MESSAGE, PrintMsgParam::REMOVE_LINE_BREAK });
this->logger->PrintMessage(" [" + filename + "]", {PrintMsgParam::DONT_USE_TRANSLATOR, PrintMsgParam::PAUSE_SCREEN });
file.close();
} |
|
ConsoleLogger.h
| C++ | 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
| #include "FileManager.h"
#include <fstream>
#include <filesystem>
#include <sstream>
#include <string>
typedef ConsoleLogger::PrintMessageParams PrintMsgParam;
FileManager::FileManager()
{ }
FileManager::FileManager(ConsoleLogger* logger)
: logger(logger)
{ }
FileManager::~FileManager()
{ }
bool FileManager::AssertFileExists(const std::string& filename, const bool& loggerAlarmRequired)
{
std::ifstream file(filename.c_str());
bool fileExists = file.good();
if (loggerAlarmRequired && logger) {
logger->PrintMessage("[" + filename + "] - ", { PrintMsgParam::SPECIAL_MESSAGE, PrintMsgParam::REMOVE_LINE_BREAK, PrintMsgParam::DONT_USE_TRANSLATOR });
if (fileExists) {
logger->PrintMessage("file_exists");
} else {
logger->PrintMessage("file_not_exists");
}
}
file.close();
return fileExists;
}
bool FileManager::IsFileEmpty(const std::string& filename, const bool& loggerAlarmRequired)
{
if (!this->AssertFileExists(filename, loggerAlarmRequired)) {
return true;
}
return this->GetFileContent(filename).empty();
}
std::vector<std::string> FileManager::GetFileContent(const std::string& filename)
{
std::vector<std::string> readingResult;
if (!this->AssertFileExists(filename, true)) {
return readingResult;
}
std::ifstream file(filename);
std::string line;
while (std::getline(file, line)) {
readingResult.push_back(line);
}
file.close();
return readingResult;
}
void FileManager::WriteContentToFile(std::vector<std::string>& lines, const std::string& filename)
{
std::ofstream file(filename, std::fstream::out);
for (std::string& line : lines) {
file << line << "\n";
}
this->logger->PrintMessage("new_data_writed_to_file", { PrintMsgParam::SPECIAL_MESSAGE, PrintMsgParam::REMOVE_LINE_BREAK });
this->logger->PrintMessage(" [" + filename + "]", {PrintMsgParam::DONT_USE_TRANSLATOR, PrintMsgParam::PAUSE_SCREEN });
file.close();
} |
|
ConsoleLogger.cpp
| C++ | 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 "ConsoleLogger.h"
#include <time.h>
ConsoleLogger::ConsoleLogger(const std::vector<ConsoleLoggerParams>& config)
: initialConfig(config)
{
this->Initialize();
}
void ConsoleLogger::Initialize()
{
auto cfgBeginPtr = this->initialConfig.begin();
auto cfgEndPtr = this->initialConfig.end();
UINT codePage = this->US_CODE_PAGE;
if (std::find(cfgBeginPtr, cfgEndPtr, ConsoleLoggerParams::ENABLE_RUSSIAN_LANGUAGE) != cfgEndPtr) {
codePage = this->RUSSIAN_CODE_PAGE;
}
SetConsoleCodePage(codePage);
this->translator.setLocale(codePage == this->RUSSIAN_CODE_PAGE ? "RU" : "EN");
}
void ConsoleLogger::PrintMessage(std::string message, const std::vector<PrintMessageParams>& params)
{
auto paramsBeginPtr = params.begin();
auto paramsEndPtr = params.end();
auto AddEmptyLine{ []() {std::cout << std::endl; } };
if (std::find(paramsBeginPtr, paramsEndPtr, PrintMessageParams::CLEAR_SCREEN) != paramsEndPtr) {
this->ClearScreen();
}
if (std::find(paramsBeginPtr, paramsEndPtr, PrintMessageParams::EXTRA_LINE) != paramsEndPtr) {
AddEmptyLine();
}
if (std::find(paramsBeginPtr, paramsEndPtr, PrintMessageParams::SPECIAL_MESSAGE) != paramsEndPtr) {
this->PrintTimestamp();
}
bool useTranslator = true;
if (std::find(paramsBeginPtr, paramsEndPtr, PrintMessageParams::DONT_USE_TRANSLATOR) != paramsEndPtr) {
useTranslator = false;
}
if (useTranslator) {
std::cout << translator.Translate(message);
} else {
std::cout << message;
}
if (std::find(paramsBeginPtr, paramsEndPtr, PrintMessageParams::REMOVE_LINE_BREAK) == paramsEndPtr) {
AddEmptyLine();
}
if (std::find(paramsBeginPtr, paramsEndPtr, PrintMessageParams::EXTRA_LINE_AT_THE_END) != paramsEndPtr) {
AddEmptyLine();
}
if (std::find(paramsBeginPtr, paramsEndPtr, PrintMessageParams::PAUSE_SCREEN) != paramsEndPtr) {
this->PauseScreen();
}
}
void ConsoleLogger::ClearScreen()
{
system("CLS");
}
void ConsoleLogger::PauseScreen()
{
system("pause");
}
void ConsoleLogger::SetConsoleCodePage(const UINT& codePage)
{
SetConsoleCP(codePage);
SetConsoleOutputCP(codePage);
}
void ConsoleLogger::PrintTimestamp()
{
time_t now = time(0);
struct tm tstruct;
char buf[80];
localtime_s(&tstruct, &now);
strftime(buf, sizeof(buf), "%Y-%m-%d %X", &tstruct);
std::string timestamp = { buf };
std::cout<< "["<< timestamp <<"]: ";
}
ConsoleLogger::~ConsoleLogger()
{
} |
|
LinesProcessor.h
| C++ | 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
| #pragma once
#include <vector>
#include <iostream>
#include "ConsoleLogger.h"
#include "FileManager.h"
#include <string>
class LinesProcessor
{
public:
LinesProcessor(ConsoleLogger* logger);
~LinesProcessor();
public:
void SetFileManager(FileManager* fManager);
void Go(std::vector<std::string>& lines);
private:
std::vector<int> GetNeededDataLinesIndexes(std::vector<std::string>& lines);
std::string DoReplaceLine(const std::string& line);
std::string GetLineForReplace();
private:
ConsoleLogger* logger;
FileManager* fm;
}; |
|
LinesProcessor.cpp
| C++ | 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
| #include "LinesProcessor.h"
LinesProcessor::LinesProcessor(ConsoleLogger* logger)
: logger(logger)
{ }
LinesProcessor::~LinesProcessor()
{ }
void LinesProcessor::SetFileManager(FileManager* fManager)
{
this->fm = fManager;
}
void LinesProcessor::Go(std::vector<std::string>& lines)
{
if (lines.empty()) {
return;
}
auto neededLinesIndexes = this->GetNeededDataLinesIndexes(lines);
if (neededLinesIndexes.empty()) {
lines.push_back(this->GetLineForReplace());
this->logger->PrintMessage("template_line_added_to_file", { PrintMsgParam::SPECIAL_MESSAGE });
return;
}
if (DEBUG_MODE) {
this->logger->PrintMessage("data_replacing_started", { PrintMsgParam::SPECIAL_MESSAGE });
}
for (UINT lineIndex : neededLinesIndexes) {
lines[lineIndex] = this->DoReplaceLine(lines[lineIndex]);
}
if (DEBUG_MODE) {
this->logger->PrintMessage("data_replacing_finished", { PrintMsgParam::SPECIAL_MESSAGE });
}
}
std::vector<int> LinesProcessor::GetNeededDataLinesIndexes(std::vector<std::string>& lines)
{
std::vector<int> neededLinesIndexes;
UINT iterator = 0;
this->logger->PrintMessage("needed_data_searching_started", { PrintMsgParam::SPECIAL_MESSAGE });
for (std::string& line : lines) {
if (line[0] == 'S' && line[1] == ' ') {
if (DEBUG_MODE) {
this->logger->PrintMessage("needed_data_found_at", { PrintMsgParam::SPECIAL_MESSAGE, PrintMsgParam::REMOVE_LINE_BREAK });
this->logger->PrintMessage(std::to_string(iterator), { PrintMsgParam::DONT_USE_TRANSLATOR });
}
neededLinesIndexes.push_back(iterator);
}
iterator++;
}
if (neededLinesIndexes.empty()) {
this->logger->PrintMessage("no_needed_data_was_detected_in_file", { PrintMsgParam::SPECIAL_MESSAGE });
} else {
this->logger->PrintMessage("needed_data_searching_ended", { PrintMsgParam::SPECIAL_MESSAGE });
}
return neededLinesIndexes;
}
std::string LinesProcessor::DoReplaceLine(const std::string& line)
{
std::string result = line;
result.replace(result.begin() + 2, result.end(), NEW_TEXT.c_str());
return result;
}
std::string LinesProcessor::GetLineForReplace()
{
return "S " + NEW_TEXT;
} |
|
Translator.h
| C++ | 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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
| #pragma once
#include <iostream>
#include <vector>
class Translator {
public:
Translator(const std::string& locale = "RU")
: locale(locale)
{ }
public:
std::string Translate(const std::string& msg) {
std::vector<std::pair<std::string, std::string>>* dictionary = locale == "RU" ? &this->ruDictionary : &this->enDictionary;
auto beginIterator = dictionary->begin();
auto endIterator = dictionary->end();
auto msgIterator = std::find_if(beginIterator, endIterator, [&msg](const std::pair<std::string, std::string>& element) {
return element.first == msg;
});
try {
if (msgIterator != endIterator) {
return msgIterator->second;
}
}
catch (...) {
return msg;
}
return msg;
}
void setLocale(const std::string& locale) noexcept{ this->locale = locale; }
private:
std::string locale;
std::vector<std::pair<std::string, std::string>> enDictionary = {
std::make_pair<std::string, std::string>(
"logger_initialized", "Logger successfully initialized"
),
std::make_pair<std::string, std::string>(
"file_manager_initialized", "File manager successfully initialized"
),
std::make_pair<std::string, std::string>(
"file_not_exists", "Current file doesn't exists"
),
std::make_pair<std::string, std::string>(
"file_exists", "Current file exists"
),
std::make_pair<std::string, std::string>(
"lines_processor_initialized", "Lines processor successfuly initialized"
),
std::make_pair<std::string, std::string>(
"no_needed_data_was_detected_in_file", "No needed data was detected in the file"
),
std::make_pair<std::string, std::string>(
"needed_data_searching_started", "Needed data searching started"
),
std::make_pair<std::string, std::string>(
"needed_data_found_at", "Needed data found at row with index: "
),
std::make_pair<std::string, std::string>(
"needed_data_searching_ended", "Needed data searching ended"
),
std::make_pair<std::string, std::string>(
"data_replacing_started", "Data replacing process has been started"
),
std::make_pair<std::string, std::string>(
"data_replacing_finished", "Data replacing process has been successfully finished"
),
std::make_pair<std::string, std::string>(
"new_data_writed_to_file", "New data has been successfully written to the file"
),
std::make_pair<std::string, std::string>(
"template_line_added_to_file", "Template line has been successfully added to file"
)
};
std::vector<std::pair<std::string, std::string>> ruDictionary = {
std::make_pair<std::string, std::string>(
"logger_initialized", "Логгер успешно инициализирован"
),
std::make_pair<std::string, std::string>(
"file_manager_initialized", "Файловый менеджер успешно инициализирован"
),
std::make_pair<std::string, std::string>(
"file_not_exists", "Данный файл не существует"
),
std::make_pair<std::string, std::string>(
"file_exists", "Данный файл существует"
),
std::make_pair<std::string, std::string>(
"lines_processor_initialized", "Обработчик строк успешно инициализирован"
),
std::make_pair<std::string, std::string>(
"no_needed_data_was_detected_in_file", "Нужной информации не было найдено в файле"
),
std::make_pair<std::string, std::string>(
"needed_data_searching_started", "Поиск нужной информации начат"
),
std::make_pair<std::string, std::string>(
"needed_data_found_at", "Нужная информация была найдена в строке под номером: "
),
std::make_pair<std::string, std::string>(
"needed_data_searching_ended", "Поиск нужной информации завершён"
),
std::make_pair<std::string, std::string>(
"data_replacing_started", "Процесс перестановки информации в строках начат"
),
std::make_pair<std::string, std::string>(
"data_replacing_finished", "Процесс перестановки информации в строках успешно закончен"
),
std::make_pair<std::string, std::string>(
"new_data_writed_to_file", "Новая информация была успешно записана в файл"
),
std::make_pair<std::string, std::string>(
"template_line_added_to_file", "Шаблонная строка была успешно добавлена в файл"
)
};
}; |
|
Config.h
| C++ | 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
| #pragma once
#include <iostream>
#include "ConsoleLogger.h"
typedef ConsoleLogger::PrintMessageParams PrintMsgParam;
typedef ConsoleLogger::ConsoleLoggerParams LoggerParam;
const std::string RUSSIAN_LOCALE = "RU";
const std::string ENGLISH_LOCALE = "EN";
const std::string SYSTEM_LOCALE = RUSSIAN_LOCALE;
const std::string FILE_FOR_PROCCESS = "source.txt";
const std::string PROCESSED_FILE = "output.txt";
const std::string NEW_TEXT = "my new replaced text";
const bool DEBUG_MODE = true; |
|
0
|