PDA

View Full Version : Best way to write to a file



The 11th plague of Egypt
25th August 2011, 13:49
I'm building a save file, I have various functions that need to write to the same file one after the other.

Right now I'm using this code to open the file and write to it.


bool someFunction(QString fileName)
{
QFile file(fileName);
if(!file.open(QIODevice::WriteOnly)) //sometimes opened in Append mode
return 0;

QDataStream out(&file);
out.setVersion(QDataStream::Qt_4_7);
out << //here goes the stuff
return 1;
}

So I open the file every time, would it be more efficient to open it just one time and then pass the various functions a pointer, like this ?

bool someFunction(QFile *file)

Or should I pass the QDataStream altogether?

bool someFunction(QDataStream out)

BTW does the file need to be closed at the end of the function?

high_flyer
25th August 2011, 13:54
The question is, how do these functions write to the file?
Do you append everything, or overwrite the file, or something else?

Did you consider using QSettings?

yeye_olive
25th August 2011, 13:59
If you write to the file in several steps, then you should only open it once. You should simply open the file and create the QDataStream, then pass a pointer or a reference to the QDataStream around (be careful, your second suggestion passes the QDataStream by value, which you do not want to do, and probably cannot do due to a non-public copy constructor).

QFile automatically closes the file in its destructor if it has not been done yet, so do not worry about it. Just make sure that the QDataStream, then the QFile get destroyed after you are done writing.

The 11th plague of Egypt
25th August 2011, 14:16
I have one function that opens the file to overwrite everything, then other functions append infos.
Maybe I should open it like this the first time

file.open(QIODevice::Truncate)
If there is no file to truncate, does it get created?

Thank you, I'll pass a reference to the QDataStream, like this

bool someFunction(QDataStream &out)

I'm saving with a .txt extension, so I can have a look when I need to debug, does it make a difference?

yeye_olive
25th August 2011, 14:43
If there is no file to truncate, does it get created?
Yes, as long as you do not forget QIODevice::WriteOnly. From the docs:

The mode must be QIODevice::ReadOnly, QIODevice::WriteOnly, or QIODevice::ReadWrite. It may also have additional flags, such as QIODevice::Text and QIODevice::Unbuffered.

I'm saving with a .txt extension, so I can have a look when I need to debug, does it make a difference?
No, the contents of the file will not be affected. However QDataStream will produce binary data; I would use a hex editor rather than a text editor.