PDA

View Full Version : Append file



mvbhavsar
10th February 2011, 08:03
Hi,

I have a file called database.h having following content.


================================================== =========
#ifndef DATABASE_H
#define DATABASE_H

#include <QtCore>
#include <QtSql>
class database
{
public:
database();
bool connectDB();

private:
QSqlDatabase db;
};

#endif // DATABASE_H
================================================== ======

Now I want to append some text in this file after finding some phrase in this.

e.g. after all #include lines I want to add #include <QtGui>
or
after private: string I want to add QSqlQuery qry;

How to achieve this using seek() function?

Thanks in advance

Manish

high_flyer
10th February 2011, 08:33
seek() alone will not do, since if you just append stuff to a certain position, it will overwrite other data in that position.
If you want to insert new content somewhere in the middle, you will have to do the following:
- Read the whole file out in to a String.
- Search the position desired (I would use QRegExp).
- Edit the string
- Write the edited string to the file - overtiring the file with the new updated data.

stampede
10th February 2011, 08:33
You can try to read the file line-by-line ( QTextStream::readLine() (http://doc.qt.nokia.com/latest/qtextstream.html#readLine) ) and use QString::indexOf() (http://doc.qt.nokia.com/latest/qstring.html#indexOf-4) to check if current line is interesting to you.
'seek()' is rather low-level compared to other convenient string search methods

camelsoft
10th February 2011, 08:38
QTextStream in("database.h", QIODevice::ReadOnly );
QString fileContent = qts.readAll();
qts.close();
//use indexOf, lastIndexOf, insert functions of QString here.
//then
QTextStream out("database.h", QIODevice::WriteOnly );
out << fileContent;
out.close();