Question

I need to read strings from foo.txt:

#include <QDebug>
#include <QFile>
#include <QStringList>
#include <QTextStream>

int main( int argc, char** argv )
{
    QFile file("foo.txt");
    if (!file.open(QIODevice::ReadOnly))
        return 1;
    QStringList stringList;
    QTextStream textStream(&file);
    textStream.readLine();
    while (!textStream.atEnd())
        stringList << textStream.readLine();

    file.close();

    qDebug() << stringList;

    return 0;
}

outPut

file opened, but textStream always empty.

Was it helpful?

Solution

From your comment it would appear that the executable is simply not finding the file as they are in different locations. There are a variety of ways to solve this and it depends on what the final use case is meant to be. Here are some ways you can solve the issue:

  • hard code in the path to the file (relative or absolute)
  • move the file to be in the same directory as the executable
  • use a command line option to tell the executable where the file is
  • use an environment variable to tell the executable where to look

For testing either of the first two options are quick and easy but you will probably want something better than that if you intend to take things further.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top