PDA

View Full Version : how can i copy a directary using QDir



monaem
30th January 2006, 14:20
hi,
i want to create a directory and copy the content of another directory on it,how can i do?

another question :
this copy contains an executing file ,and i want to launch this execution using a qpushButton in a form, any answer ?


regards.

guilugi
30th January 2006, 14:44
Hello,

With QDir, you have the method mkpath to creat a full path (including parent directories that don't exist yet), really useful.

Then to copy a file, you should use QFile::copy(QString sourceFile, QString outputFile)...;)

There is no copy function in QDir, so you have to do a simple loop to copy a whole directory...by doing this, you can also connect a progressbar to monitor the copy process !

Guilugi.

guilugi
30th January 2006, 14:46
Ooops,

For your second question, it's also really simple.

You connect your push button to a dedicated slot, that will start a QProcess linked to your executable, with all the arguments you want !
Just check the docs ;)

Guilugi.

monaem
30th January 2006, 15:32
but this directory contains other directories,how can i do?

yogeshm02
30th January 2006, 15:55
but this directory contains other directories,how can i do?

I have given below a trimmed down version which I used in an app. You still need to do some work.


.
#include <dirent.h>
#include <sys/stat.h>

void copy(QString dir){
DIR * d = opendir(QFile::encodeName(dir));
dirent *ent;
if(d == NULL)//Non-readble
return;
//code for copying dir goes here ---------------------------- 1 ------------------------------
.
.
while((ent = readdir(d))){
QByteArray entry = ent->d_name;
if( entry == "." || entry == ".." )
continue;
entry.prepend( QFile::encodeName( dir.endsWith( "/" ) ? dir : dir + "/" ) );
if(stat(entry, &statBuf) == 0){
if(S_ISREG(statBuf.st_mode)){
QString file_name_with_path = QString::fromLocal8Bit(entry);
//code for copying file goes here
}
if(S_ISDIR(statBuf.st_mode)){
QString dir_name_with_path = QString::fromLocal8Bit(entry);
//code for copying dir goes here ---------- same as 1-----------------------
.
.
copy(dir_name_with_path);
}
}
}
closedir( d );
}

wysota
4th February 2006, 13:12
Ok, this doesn't look very "Qt-ish". How about:


bool copyDir(const QString &src, const QString &dest){
QDir dir(src);
QDir dirdest(dest);
if(!dir.isReadable()) return false;
QFileInfoList entries = dir.entryInfoList();
for(QList<QFileInfo>::iterator it = entries.begin(); it!=entries.end();++it){
QFileInfo &finfo = *it;
if(finfo.fileName()=="." || finfo.fileName()=="..") continue;
if(finfo.isDir()){ copyDir(finfo.filePath()); continue; }
if(finfo.isSymLink()) { /* do something here */ continue; }
if(finfo.isFile() && file.isReadable()){
QFile file(finfo.filePath());
file.copy(dirdest.absoluteFilePath(finfo.fileName( )));
} else return false;
}
return true;
}

I didn't compile/test it, so it may not work, but shows the right direction.