0

My problem is simple enough but I'm not able to fix this...

In my header:

QTextStream *in = NULL;

in one method the QTextStream gets initialized:

in = new QTextStream(&file);

then I am trying to parse it in another method:

QString next;

if(in != NULL){
    while(!in->atEnd()){
        next = in->readLine();
    }
}
else{
  QMessageBox::critical(this, "Error", "No file to test!");
}

While initializing works fine, the app crashes at the test if in is atEnd(). What am I doing wrong? I need in to be accessible from several methods. I have to use a pointer here (?) because in gets initialized later (AFAIK that's not possible with references)

It might be obvious but I'm fairly new to c++...

Thank you!

TheDarkKnight
  • 27,181
  • 6
  • 55
  • 85
  • 1
    You don't have to use pointers. You can also declare `QTextStream in` and `QFile file` as member variables of your class. Use [`QTextStream::setDevice()`](http://qt-project.org/doc/qt-5.0/qtcore/qtextstream.html#setDevice) function to set `file` as the device for your `in` object. – thuga Oct 31 '13 at 13:30
  • Maybe just QFile as a class member and QTextStream as a local variable to whatever method that processes the file. Or just store the filename in a QString and open it in the method that processes with local QFile and process it with a local QTextStream. – drescherjm Oct 31 '13 at 13:32
  • How do you open the file? I always call QString data = file->readAll(), then call `in = new QTextStream(&data);` – Alex Hendren Oct 31 '13 at 16:23

1 Answers1

6

I see that you initialize the text stream with &file. It looks like file is a local variable and it is destroyed when initialize function is completed. QTextStream expects the IO device passed to be valid until the stream is destroyed. So you get the segfault. You need to make sure that file is not destroyed while text stream is used.

Pavel Strakhov
  • 39,123
  • 5
  • 88
  • 127
  • Thanks for the input! It's true that I am closing the file, but even if I let it open I receive the same error. – user2923837 Oct 31 '13 at 13:52
  • @user2923837 that is expected with the code you are using. When QFile goes out of scope it closes the file internally and even if it did not it would not solve your problem since your QFile must exist as long as your QTextStream. – drescherjm Oct 31 '13 at 13:57
  • @user2923837: Basically this is not a Qt issue at all, it's lack of understanding of the very basics of C++. – Kuba hasn't forgotten Monica Oct 31 '13 at 20:58