aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorJan Tuomi <jan-sebastian.tuomi@aalto.fi>2016-10-09 13:44:06 +0300
committerJan Tuomi <jan-sebastian.tuomi@aalto.fi>2016-10-09 14:50:24 +0300
commit40c4dfd312b24a7e012448e39a363c07fa1e8c5d (patch)
tree6f287e601a9f94e12d2efb0b5720db5adef650a9
parent43fe02ecb4c1c99e4d942488e8982890d8c6a8d7 (diff)
Add writing to file
-rw-r--r--editor.cpp36
-rw-r--r--editor.h5
-rw-r--r--main.cpp2
3 files changed, 39 insertions, 4 deletions
diff --git a/editor.cpp b/editor.cpp
index 28bd081..27169ef 100644
--- a/editor.cpp
+++ b/editor.cpp
@@ -1,10 +1,11 @@
#include "editor.h"
#include "utils.h"
+#include <fstream>
#include <limits>
#include <iostream>
-Editor::Editor(std::vector<std::string>* contents):
- m_current_line(0) {
+Editor::Editor(std::vector<std::string>* contents, const std::string& filename):
+ m_current_line(0), m_filename(filename) {
m_contents = contents;
}
@@ -24,6 +25,9 @@ int Editor::run_editor() {
case 'm':
move_to_command();
break;
+ case 'w':
+ write_command();
+ break;
default:
break;
}
@@ -80,3 +84,31 @@ int Editor::move_to_line(int line) {
m_current_line = line;
return 0;
}
+
+int Editor::write_command() {
+ std::cout << "Write to file? [y/n] ";
+ char answer = Utils::getch();
+
+ if (answer == 'y') {
+ return write();
+ }
+
+ return 0;
+}
+
+int Editor::write() {
+ std::ofstream file;
+ file.open(m_filename);
+ if (file.fail()) {
+ std::cout << "Can't open file " << m_filename << " for writing!";
+ return 1;
+ }
+
+ for (int i = 0; i < m_contents->size(); i++) {
+ file << m_contents->at(i) << '\n';
+ }
+
+ file.close();
+
+ return 0;
+}
diff --git a/editor.h b/editor.h
index 1ae2a51..9d2a773 100644
--- a/editor.h
+++ b/editor.h
@@ -6,20 +6,23 @@
class Editor {
public:
- Editor(std::vector<std::string>* contents);
+ Editor(std::vector<std::string>* contents, const std::string& filename);
int run_editor();
private:
const static int OUTPUT_LINE_MAX = 10;
std::vector<std::string>* m_contents;
+ std::string m_filename;
int m_current_line;
int print_contents_on_line(int line) const;
int edit_command();
int move_to_command();
+ int write_command();
int edit_line(int line);
int move_to_line(int line);
+ int write();
};
#endif
diff --git a/main.cpp b/main.cpp
index 6378f1e..20a5f2d 100644
--- a/main.cpp
+++ b/main.cpp
@@ -32,7 +32,7 @@ int main(int argc, char** argv) {
return 1;
}
- Editor editor(contents);
+ Editor editor(contents, filepath);
editor.run_editor();
delete contents;