-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRedirection.cpp
44 lines (40 loc) · 1018 Bytes
/
Redirection.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
#include "Redirection.h"
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
bool Redirection::redirectInput(std::string& input) {
if (type == Input && !file.empty()) {
std::ifstream inputFile;
inputFile.open(file);
if (!inputFile.is_open()) {
std::cerr << "Error: File \"" << file << "\" does not exist." << std::endl;
return false;
}
std::stringstream buffer;
buffer << inputFile.rdbuf();
input = buffer.str();
inputFile.close();
return true;
}
return false;
}
bool Redirection::redirectOutput(std::string output) {
if ((type == Output || type == Append) && !file.empty()) {
std::ofstream outputFile;
if (type == Output) {
outputFile.open(file, std::ios::trunc);
}
else if (type == Append) {
outputFile.open(file, std::ios::app);
}
if (!outputFile.is_open()) {
std::cerr << "Error: File \"" << file << "\" does not exist." << std::endl;
return false;
}
outputFile << output;
outputFile.close();
return true;
}
return false;
}