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 http://docs.wxwidgets.org/stable/wx_wxtextinputstream.html#wxtextinputstream


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();
Personal tools