wxFileInputStream always goes to the end of file (Eof) Topic is solved

If you are using the main C++ distribution of wxWidgets, Feel free to ask any question related to wxWidgets development here. This means questions regarding to C++ and wxWidgets, not compile problems.
Post Reply
User avatar
Azrael
Knows some wx things
Knows some wx things
Posts: 37
Joined: Sat Aug 05, 2017 2:44 pm
Location: Italy

wxFileInputStream always goes to the end of file (Eof)

Post by Azrael »

Hello everyone,
I want to read strings from a file but the code I wrote doesn't seem to work. Every time I call the function I get my message "Reached end of file". It never enters the while loop and I don't understand why. The file is not empty. I should be able to get the string out of it, no?

Code: Select all

void load(){
    wxFileInputStream file(wxT("../myFile.txt"));
    if(file.IsOk()){
        wxTextInputStream text(file);
        if(!text.ReadLine().IsSameAs(wxEmptyString)){
           while(!file.Eof()){
                wxString line = text.ReadLine();
                wxMessageBox(wxT("I'm here"));
           }

           if(file.Eof()) {
                    wxMessageBox(wxT("Reached end of file! Loading completed! "));
           }
        }    
     }   
}
User avatar
xaviou
Super wx Problem Solver
Super wx Problem Solver
Posts: 437
Joined: Mon Aug 21, 2006 3:18 pm
Location: Annecy - France
Contact:

Re: wxFileInputStream always goes to the end of file (Eof)

Post by xaviou »

Hi.

The problem is that the wxTextFile loads the entire content of the file into memory, so when you start the loop, the wxFileInputStream has already reached its end.

2 thing you can do :
  • You don't have to use the wxFileInputStream : wxTextFile can read a real file itself
  • Use the wxTextFile Eof() function as your loop condition
Regards.
Xav'
My wxWidgets stuff web page : X@v's wxStuff
User avatar
Azrael
Knows some wx things
Knows some wx things
Posts: 37
Joined: Sat Aug 05, 2017 2:44 pm
Location: Italy

Re: wxFileInputStream always goes to the end of file (Eof)

Post by Azrael »

xaviou wrote: 2 thing you can do :
  • You don't have to use the wxFileInputStream : wxTextFile can read a real file itself
  • Use the wxTextFile Eof() function as your loop condition
I used both of them and it works now. Thank you!

Code: Select all

wxTextFile text(wxT("../myFile.txt"));
text.Open();
if (!text.GetFirstLine().IsSameAs(wxEmptyString)) {
    wxArrayString tmp ;
    for (auto str = text.GetFirstLine(); !text.Eof(); str = text.GetNextLine()) {
        tmp.Add(str);       
    }
    if (text.Eof()) {
        wxMessageBox(wxT("Reached end of file! Loading completed! "));
    }
    text.Close();
    addFile(&tmp);
}
Post Reply