I have written this piece of code as a function, each time I call this function, I want to write to the file.But this function writes only once to the file.whenever I open the file from windows I find only one word written to the file. How to write in the file continuously each time I call?
/* Try and open a file for output */
QString outputFilename = "Results.txt";
QFile outputFile(outputFilename);
outputFile.open(QIODevice::WriteOnly);
/* Check it opened OK */
if(!outputFile.isOpen()){
qDebug() <<"- Error, unable to open" << outputFilename << "for output";
return ;
}
/* Point a QTextStream object at the file */
QTextStream outStream(&outputFile);
/* Write the line to the file */
outStream <<"\n"<< szTemp;//"Victory!\n";
/* Close the file */
outputFile.close();
When the line outputFile.open(QIODevice::WriteOnly);
opens the file, it replaces everything that was already in the file. Try replacing the line with:
outputFile.open(QIODevice::Append);
to open it in a mode that instead appends the data to whatever exists in the file.
Note that opening the file for every single line is an inefficient solution, especially if you have many, many lines to write. Opening the file once, then writing all the words to it before closing it, would work faster.