0

I tried to use QTextStream to read data from xml file,but at last I got empty string. Here is my code:

QFile f("note.xml");
if(f.open(QIODevice::ReadWrite)){
    QTextStream in(&f);
    in.setCodec("UTF-8");
    qDebug()<<in.readAll();
}else qDebug()<<"failed";

Here is the content of xml file:

<?xml version="1.0" encoding="UTF-8" ?>
<note>
<to>George</to>
</note>

I am using Qt_version 5.1.1 and MinGW_32bit-Debug, Windows 7.If I change xml file to txt file,the result is still empty string.

camperr
  • 9
  • 1
  • 4
  • Does `QFile::open` return true? Does `f.readAll()` return any data? – hank Oct 25 '13 at 11:28
  • `QFile::open` reutrn true and no data is returned by `f.readAll()` – camperr Oct 25 '13 at 11:41
  • 1
    Make sure the file you open exists. Try to open it with `QIODevice::ReadOnly` flag, because `QIODevice::ReadWrite` flag automatically creates an empty file if the specified file doesn't exist. – hank Oct 25 '13 at 11:44
  • Now `QFile::open` return false.But I'm very sure the file exists. – camperr Oct 25 '13 at 12:03

1 Answers1

3

I think your problem might be related to the fact that you are not passing the full path to the QFile constructor. If the file in not located in the current path, the call to QFile::open might succeed (perhaps because you are opening in read AND write mode) creating a new file, and thus the read returns an empty string. To avoid that, you can check if the file exists. Try changing the code to something like this:

QFile f("/complete-path/note.xml");
if(f.exists() && f.open(QIODevice::ReadWrite) {
    . . .

EDIT: As Hank just suggested in a commentary. :)

Luiz Vieira
  • 570
  • 11
  • 35
  • 1
    ReadOnly is better, here you have a potential race if the file is deleted between exists() and open(). – Frank Osterfeld Oct 25 '13 at 12:16
  • Thank you.I get the right result using full file path.But my code files and xml file are in the same directory, why I cannot just use the filename. – camperr Oct 25 '13 at 12:20
  • @camperr Your file must be in the same directory as your executable. – hank Oct 25 '13 at 12:27
  • @hank Do you mean the file must be in the same directory with the .exe file? – camperr Oct 25 '13 at 12:39
  • if you are using Qt Creator most probably you have active shadow build: executable is located in different location the your project file and most probably your xml file. Disable shadow build or copy you file to executable location (shadow build location, usually something like `../-`). – Marek R Oct 25 '13 at 15:03