1

I want to read a file and to put it in a Qstring but the file doesn't be read I have searched for many sample in google but it doesn't work... I want read the file...

using namespace std;

 int main(int argc, char *argv[])

 {

    QApplication app(argc, argv);


    QFile in1("file.txt");

    QTextStream in(&in1);

    if (in1.open(QFile::ReadOnly | QFile::Text))
    {
        QLabel *label = new QLabel("read");
        label->show();
    }

    if (!in1.open(QFile::ReadOnly | QFile::Text))
    {
        QLabel *label = new QLabel("!read");
        label->show();
    }
    QString s1;

    in >> s1;

    QLabel *label = new QLabel(s1);

    label->show();

    return app.exec();

 }

show me: !read

I included everything that you can think and file.txt is in true place ??!! :-(

László Papp
  • 51,870
  • 39
  • 111
  • 135
eci_small
  • 13
  • 2
  • Please indent your code properly – Kirell Dec 28 '13 at 15:35
  • For me, it shows `read`, then `!read` (please note that open is called twice; please use `else` instead of `if (!...)`; in your code even if the first open is successful, the second is not because it's already opened) and then the contents of the file as expected. Are you sure you placed the file in the **build directory**? – leemes Dec 28 '13 at 16:01
  • What do you mean with "will not work"? In my case, the content was a single word; the OP's code reads one word, so it worked. It wasn't me who decided to read only a single word ;) I should have written "the first word" instead of "the contents". The question is about opening a file, I guess, and the read operation is only a simple test to see if it really worked. – leemes Dec 28 '13 at 16:12
  • ok it was worked thanks everyone but I want to read word by word not readAll() or readLine() ??? – eci_small Dec 28 '13 at 18:07

1 Answers1

0

This code works for me below.

file.txt

Hello World!

main.cpp

#include <QLabel>
#include <QApplication>

#include <QFile>
#include <QTextStream>
#include <QString>
#include <QDebug>

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    QFile in1("file.txt");
    QTextStream in(&in1);

    if (in1.open(QFile::ReadOnly | QFile::Text))
    {
        QLabel *label = new QLabel("read");
        label->show();
    }

    if (!in1.open(QFile::ReadOnly | QFile::Text))
    {
        QLabel *label = new QLabel("!read");
        label->show();
    }

    QString s1;
    in >> s1;

    QLabel *label = new QLabel(s1);
    label->show();
    return app.exec();
}

Build

g++ -Wall -fPIC -lQt5Core -lQt5Widgets -I/usr/include/qt -I/usr/include/qt/QtCore -I/usr/include/qt/QtWidgets main.cpp && ./a.out

or the main.pro qmake project file:

TEMPLATE = app
TARGET = main
greaterThan(QT_MAJOR_VERSION, 4):QT += widgets
SOURCES += main.cpp

It will show all the three labels for me, but I am not sure if that is what you wanted. The error handling is missing in your code, too.

László Papp
  • 51,870
  • 39
  • 111
  • 135