PDA

View Full Version : update .txt file



phillip_Qt
22nd June 2010, 11:26
Hi ALL,
I'm trying to create a file and update some data in the file.

e.g Data is like

Helllo
Hi
Qt
Test

Below is my code. but last line is overwriting. Ineed new text to be insert a new line and append the string. Plz tell me how to correct this code snipset.


#include <QtCore/QCoreApplication>
#include <iostream>
#include <qfile.h>
#include <qtextstream.h>
using namespace std;


void File(QString myFilename, QString myData)
{
QFile file(myFilename);
if ( file.open( QIODevice::ReadWrite) )
{
QTextStream stream( &file );


// while (stream.atEnd())
// {
// stream << QChar((int)'\n');
//
// }
stream <<myData << endl;

}
else
{
qDebug( "Could not create file %s" );
}
}

int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);

QString file("D:\\test.txt");

File(file, "1St Line: Hello");
File(file, "2Nd Line : Hi");
File(file, "3rd Line : Qt");
File(file, "4th Line : Test");
return a.exec();
}


Thank u all,
Phillip

tbscope
22nd June 2010, 11:40
QIODevice::Append

phillip_Qt
22nd June 2010, 11:46
Thank u verymuch. But its not appending in new line. can u plz tell me how to append at new line?

Zlatomir
22nd June 2010, 12:17
Open the text file with wordpad. (i don't know the exact explanation why notepad doesn't show them, but new-lines are there)

ChrisW67
23rd June 2010, 01:44
If you are on Windows then you may need the QIODevice::Text flag to cause the end-of-line conversion from "\n" to "\r\n".