Search code examples
c++wxwidgets

How do I save/load information onto/from my device?


I'm developing an application, but I need it to save its information onto the computer, and load it from there next time it's opened.

To give the simplest example: I have an array of strings and I want to save them as a *.txt file in the application's directory. And every member of the array should be on a new row of the file. And I want to load the entries of the file into the array when I open the app, or create an empty *.txt file, if one doesn't exist.

Note: if there is an easier way to do this, instead of saving them into a *.txt, please tell me. Saving them strictly as a *.txt format isn't mandatory.

Also, I am using wxWidgets for my application, if it's gonna make it any easier.


Solution

  • MainFrame::MainFrame() {
        wxFileName f(wxStandardPaths::Get().GetExecutablePath());
        wxString appPath(f.GetPath());
    
        std::ifstream inputFileStream;
        inputFileStream.open(std::string(appPath.mb_str(wxConvUTF8)) + "data.txt");
        std::string data;
        inputFileStream >> data;
    }
    MainFrame::~MainFrame()
    {
        wxFileName f(wxStandardPaths::Get().GetExecutablePath());
        wxString appPath(f.GetPath());
    
        std::ofstream outputFileStream;
        outputFileStream.open(std::string(appPath.mb_str(wxConvUTF8)) + "data.txt");
        std::string data = "something";
        outputFileStream << data;
        outputFileStream.close();
    }
    

    When frame is created, I get the data. When frame is destroyed, I save the data. I don't use C++ standard library classes, but wxWidgets classes and methods for UTF-8 support. (I haven't checked if this piece of code works – it's taken from my old project.)