PDA

View Full Version : Creating QFile Objects in a loop



sky
3rd December 2010, 08:25
Hi All,

I have a quick question:

I have a dir which has a huge number of files in it. I need to iterate through all the files and open them.



while (qdirIterator.hasNext())

{
QString fileName = qdirIterator.next();
QFileInfo fileInfo = qdirIterator.fileInfo();

QFile inFile( fileInfo.absoluteFilePath() );

if( !inFile.open( QIODevice::ReadOnly | QIODevice::Text ) )
{
qCritical( "Failed to open file for reading." );
return;
}
.
.
.
} // while


First up when I look at this code I feel I am constructing too many QFile objects. So I want to do the following:



QFile inFile;
while (qdirIterator.hasNext())
{
QString fileName = qdirIterator.next();
QFileInfo fileInfo = qdirIterator.fileInfo();

if( !inFile.open( fileName, QIODevice::ReadOnly | QIODevice::Text ) )
{
qCritical( "Failed to open file for reading." );
return;
}
.
.
.
inFile.close();
} // while


Problems with this are:

1. "QFile:: open" does not take QString as an argument.
2. And even if I manage to use "QFile:: open" in this manner the docs say, "When a QFile is opened using this function, close() does not actually close the file, but only flushes it."

So is there a workaround for 1. and also make sure that "QFile:: close()" actually closes the file and not just flush it?

Thanks in Advance,
sky.

tbscope
3rd December 2010, 08:27
First up when I look at this code I feel I am constructing too many QFile objects.
You're only constructing one file at a time.
The QFile will go out of scope (destroyed) every iteration.