Reading text from a file

From WxWiki
Jump to: navigation, search

Here's a small code snippet showing how you can read read text from a file

#include <wx/textfile.h>
...
wxString        file;
wxFileDialog    fdlog(this);

// show file dialog and get the path to
// the file that was selected.
if(fdlog.ShowModal() != wxID_OK) return;
file.Clear();
file = fdlog.GetPath();

wxString        str;

// open the file
wxTextFile      tfile;
tfile.Open(file);

// read the first line
str = tfile.GetFirstLine();
processLine(str); // placeholder, do whatever you want with the string

// read all lines one by one
// until the end of the file
while(!tfile.Eof())
{
    str = tfile.GetNextLine();
    processLine(str); // placeholder, do whatever you want with the string
}

Another way : see https://docs.wxwidgets.org/stable/wx_wxtextinputstream.html#wxtextinputstream

Yet another way, with streaming (for bigger files) :

#include <wx/wfstream.h>
#include <wx/txtstrm.h>

wxFileInputStream input(wxT("c:\\somefile.txt"));
wxTextInputStream text(input, wxT("\x09"), wxConvUTF8 );
while(input.IsOk() && !input.Eof() )
{
  wxString line=text.ReadLine();
  // do something with the string
}

And now a small example of how to write a text file

#include <wx/textfile.h>
...
wxTextFile file( wxT("/path/to/my_file.txt") );
file.Open();

file.AddLine( wxT("Hello world") );
file.AddLine( wxT("This is wxTextFile") );

file.Write();
file.Close();