Created
February 22, 2013 04:36
-
-
Save berodam/5010758 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* | |
| * More permanent storage solution | |
| * | |
| */ | |
| #include <iostream> | |
| #include <fstream> | |
| #include <list> | |
| #include <string> | |
| //For testing | |
| #include <stdio.h> | |
| #include <assert.h> | |
| //Make permanent list, i.e. save it in a file | |
| void MakePermaList(std::string filename, std::list<int> permaList) | |
| { | |
| //declare an output file variable | |
| std::ofstream outfile; | |
| //open outfile for input only | |
| outfile.open(filename.c_str()); | |
| //loop through the list and write each value on a separate line | |
| for (std::list<int>::iterator i=permaList.begin(); i!=permaList.end(); ++i) | |
| { | |
| //write the values in the file, separated by endl symbol | |
| outfile << *i << std::endl; | |
| } | |
| //close the outfile | |
| outfile.close(); | |
| } | |
| //Read previously saved list | |
| std::list<int> ReadPermaList(std::string filename) | |
| { | |
| std::ifstream infile; | |
| std::list<int> outlist; | |
| int line; | |
| //open the input file | |
| infile.open(filename.c_str()); | |
| //as long as the file is not corrupted keep going | |
| while (infile.good()) | |
| { | |
| //push the vaule from the stream to line | |
| infile >> line; | |
| //if it is still not the end of the file, push int to list | |
| if (!infile.eof()) | |
| { | |
| //push line int on the list | |
| outlist.push_back(line); | |
| } | |
| } | |
| //close the input file | |
| infile.close(); | |
| //return the list | |
| return outlist; | |
| } | |
| int main() | |
| { | |
| //define file name | |
| std::string filename = "foo"; | |
| //create a standard list | |
| std::list<int> myList (2,50); | |
| //call MakePermaList to store it on the HDD | |
| MakePermaList(filename, myList); | |
| /* | |
| * We made a permanent copy. We can now remove the list from memory | |
| * and get back to it later, or just keep it and have a backup on HDD | |
| * | |
| */ | |
| //read the list | |
| std::list<int> myPermaList = ReadPermaList(filename); | |
| //check if myList and myPermaList is the same | |
| assert(myList == myPermaList); | |
| std::cout << "Success! Both of the lists are the same" << std::endl; | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment