It is necessary to transfer the text from the file to the QString variable, but when executing, the string remains empty:

 QFile file("file.txt"); file.open(QIODevice::ReadOnly); QString s; QTextStream str(&file); s.append(str.readAll()); qDebug()<<str.readAll(); file.close(); 

    2 answers 2

    Most likely, the file is simply not located. Check whether the file is open before working with it:

     QFile file("file.txt"); if(file.open(QIODevice::ReadOnly)) { QTextStream str(&file); QString s = str.readAll(); qDebug() << s; file.close(); } 

    And you can even easier:

     QFile file("file.txt"); if(file.open(QIODevice::ReadOnly)) { QString s = file.readAll(); qDebug() << s; file.close(); } 

    As I wrote - I noticed, you readAll() calls for qDebug() on the stream object, although you should output s . This may also give an empty output (the documentation does not mention what readAll() does with the internal state of the stream)

    • Stupid question but how to tell him the tea file is at the root of the project. Write simply "file.txt" is not an option. When writing a path such as "D: \\ file.txt" everything works - Alexander Startsev
    • It depends on the текущей директории , which is set by the program from which you run your application. For example, if you put the file next to the binary and run it from the explorer (as I understand it, you have windows), then the file will be read correctly. I do not know what IDE you are using, but for Visual studio, by default, the текущая директория is where the project file is located. This can be changed in the свойствах проекта(вкладка Debugging)->Working Directory - ixSci

    If you are working in QtCreator, and run through it, then you can view the working directory in the "Projects" tab (the menu of icons on the left). Then in the launch tab, the item "Working directory"