PDA

View Full Version : Problems writing to file



DiamonDogX
24th April 2009, 13:58
I have a logging class that I wish to use to append messages to a file. Naturally, I wrote a write(QString msg) for my class that I wish clients to be able to call in order to append a message to the current log file. But I can't seem to successfully write to the file... it seems to have a problem with how I am using my member variables. I have successfully written to a file like this, but only when I open it and write to it in one block of code (like how you see here: http://www.digitalfanatics.org/projects/qt_tutorial/chapter08.html). Here's my code that isn't working (_fileTextStream is a member variable of type QTextStream):


Logger::Logger()
{
QFile file( "log.txt" );
if ( !file.open( QIODevice::WriteOnly | QIODevice::Append | QIODevice::Text ) )
{
QMessageBox::critical( NULL,
tr("Error opening log file for writing."),
tr("Couldn't open file: %1").arg( file.errorString() ) );
}

QTextStream _fileTextStream( &file );
}


void Logger::write( QString message )
{
_fileTextStream << message << endl;
}

Lykurg
24th April 2009, 15:11
Logger::Logger()
{
QFile file( "log.txt" );
if ( !file.open( QIODevice::WriteOnly | QIODevice::Append | QIODevice::Text ) )
{
QMessageBox::critical( NULL,
tr("Error opening log file for writing."),
tr("Couldn't open file: %1").arg( file.errorString() ) );
}

QTextStream _fileTextStream( &file );
}


void Logger::write( QString message )
{
_fileTextStream << message << endl;
}

In that code _fileTextStream is only a local variable and therefore your code is not working. Make _fileTextStream a real member variable and use QTextStream::setDevice().

Edit:

class Logger
{
//....
private:
QTextStream _fileTextStream;
}

Logger::Logger()
{
//..
_fileTextStream.setDevice(&file);
}

DiamonDogX
24th April 2009, 15:34
That did not seem to fix the problem... the file is still not written to.

mcosta
24th April 2009, 16:01
The problem is QFile is destroyed when constructor terminate.
QFile automatically close the file controlled when the object is destroyed