PDA

View Full Version : QFile and setTextMode



lyuts
26th April 2009, 13:19
Hi, guys.

I was just experimenting with QFile and reading a random file line by line and got this question. Here is what i tried



#include <QFile>
#include <QStringList>

#include <QtDebug>

int main(int argc, char *argv[])
{
QStringList list;

list << "Makefile";

QList<QString>::const_iterator it;

for (it = list.begin(); it != list.end(); ++it) {

QFile file((*it));
//file.setTextModeEnabled(true);

if (file.open(QFile::ReadOnly)) {

char buf[1024];

while ( 0 < file.readLine(buf, sizeof(buf)) ) {
qDebug() << buf;
}

file.close();

} else {
qDebug() << "main> Unable to open file " << (*it);
}
}

return 0;
}


Note that setTextMode is commented.

The i run the program and see the file printed line by line and it is ok.

But, if uncomment setTextMode line, compile this program and run it again i always get this error:



QFile::open: File (Makefile) already open


As far as i know the setTextMode set to true takes care of end-of-line conversion only.

Why does this happen?

Thanks.

roxton
26th April 2009, 17:21
Try to avoid setTextModeEnabled() and open the file in a text mode:


if (file.open(QIODevice::ReadOnly | QIODevice::Text))

lyuts
26th April 2009, 17:28
Thanks.
I know that this way works, but it is very interesting to know the reason of that behavior with setTextMode.

sophister
27th April 2009, 07:41
I have run your codes on my computer, and I face the same problem.
Learning……
Good luck!

mcosta
27th April 2009, 19:37
I suppose you must use QIODevice::setTextModeEnabled on a opened File

sophister
28th April 2009, 05:38
if we use QIODevice::setTextModeEnabled on an opened file, the status of the file cannot be shown on the screen. There is no difference between set this true and false.

mcosta
28th April 2009, 08:37
From Qt Documentation


void QIODevice::setTextModeEnabled ( bool enabled )

If enabled is true, this function sets the Text flag on the device; otherwise the Text flag is removed. This feature is useful for classes that provide custom end-of-line handling on a QIODevice.

seems that you can use the function to customize end of line handling for QIODevice subclass