PDA

View Full Version : out Text file



valgaba
4th January 2012, 19:48
According to this code .....


QDateTime dateTime = QDateTime::currentDateTime();
QString Hora = dateTime.toString("hh:mm:ss");
QString Fecha = dateTime.toString("dd-MM-yy");

QString Path=QCoreApplication::applicationDirPath().toLati n1();

QFile file(Path + "/Logs/" + Fecha + ".txt");
file.open(QIODevice::WriteOnly| QIODevice::ReadOnly| QIODevice::Text);



QTextStream out(&file);

while (!out.atEnd()) {
QString line = out.readLine();

}


out << Hora ;
out << "\n";


file.close();


}

The output file for example is:

10:30:20
10:30:21
10:30:22
10:30:23
....
...
....
How can we make the output be:?
10:30:23
10:30:22
10:30:21
10:30:20
....
...
....

thanks

SIFE
4th January 2012, 22:16
First, read the file in QStringList then use the method sort() (http://developer.qt.nokia.com/doc/qt-4.8/qstringlist.html#sort).

ChrisW67
4th January 2012, 23:49
Line 5 and 7 select a location for log files that is not likely to be writeable when the application is deployed to "Program Files" on Windows Vista/7.
Line 8 could use QIODevice::ReadWrite for better readability. Random access to text files is unusual though.
Are you trying to append to the file by moving to the end of the existing file with the while() loop at line 14? Have you tried QIODevice::Append as the open mode?

The code you show writes a single line to the file, and not strongly connected to your question. Your question is either about:

Sorting the lines in the log file after a number are written: see valgaba's response.
Writing each new line to the top of the text file rather than the bottom.


If you want to insert a text record to the front of a file you need to:

Create a temporary file
Write the new record to the temporary file.
Open the target file
Read all the lines from the target file and append these to the temporary file
Close the target file
If successful, delete the target file and rename the temporary file.

This is an expensive operation so think hard about whether you really need this if it is a frequent event.