/* reverse.cpp - Matt Mahoney, mmahoney@cs.fit.edu This program reads lines of text from a file and writes them to another file in reverse order. The input and output file names are given on the command line. For instance, if input.txt contains: This is a test. Then the command: reverse input.txt output.txt creates output.txt as follows: test. is a This If the file names are not specified or cannot be found or created, then an error message is printed to standard error. */ #include #include #include #include using namespace std; /* A Stack stores strings. Strings are removed (popped) in the reverse order in which they were are added (pushed). Attempting to pop an empty stack throws Stack::Error. Stack st; // Initially empty stack of strings st.push(s); // Push string s onto Stack st s = st.pop(); // Pop and return string s. If empty, throws Stack::Error st.empty(); // true if empty Stack::Error; // An exception type */ class Stack { private: vector v; // The top is at the back public: class Error {}; // Exception type bool empty() const {return v.empty();} void push(const string& s) {v.push_back(s);} string pop(); }; string Stack::pop() { if (empty()) throw Error(); string s=v.back(); v.pop_back(); return s; } // Read file argv[1] and write to argv[2] with the lines in reverse order. int main(int argc, char** argv) { // Check for 2 file name arguments, exit with an error if not. if (argc<3) { cerr << "Usage: reverse inputfile outputfile\n"; return 1; } // Open input file, check for error. ifstream in(argv[1]); if (!in) { cerr << "File not found: " << argv[1] << endl; return 1; } // Open output file, check for error. ofstream out(argv[2]); if (!out) { cerr << "Cannot create file: " << argv[2] << endl; return 1; } // Read input file into stack Stack st; string s; while (getline(in, s)) st.push(s); // Write stack contents to output file try { while (true) out << st.pop() << endl; } catch (Stack::Error x) {} return 0; }