我现在要做一个批量打包文件的程序。
需要实现的功能:用户进入某一个文件夹,点击刷新然后在QTreeWidget显示这个文件夹下的所有文件,用户勾选完需要打包的文件,并选好文件保存路径,打包这些文件。
实现方法:我是将这些文件的相对路径保存到一个QStringList里面( filePathes),然后分组执行,一组十个文件(因为先前把fileathes里所有路径保存到一个QString里,会因为字符串太长,导致Cygwin死掉),利用QProcess调用外部程序Cygwin执行打包。
遇到的问题:
1.文件路径里包含空格则本组不成功,返回的exitCode=2。所以我将文件路径中的空格换成\加空格。
2.新问题:文件路径中包含一些非字母字符(如:( + )& 等)的文件无法打包。返回的exitCode=2或127,所以我将每个文件路径用双引号包起来,并取消上面的空格替换
3.新问题:一组的十个文件的最后一个文件如果包含空格,则本组不成功,返回的exitCode=2;(如果最后一个文件的路径不包含空格,前面的文件包含空格也能成功!很诡异~)
4.一直没解决的问题:文件路径包含中文,不成功;创建的tar文件包含中文,不成功。
求大牛给予建设性意见!!!!!
void ListFile::saveTar(const QString tarPath, const QString rootPath, const QStringList filePathes) //打包文件
{
QString tarName = QString("%1%2%3") //由于调用Cygwin,tar文件路径需要修改
.arg("/cygdrive/")
.arg(tarPath.at(0))
.arg(tarPath.right(tarPath.size() - 2));
int maxSize = (filePathes.size()) / 10;
if(filePathes.size()%10 != 0)
maxSize++;
ui.progressBar->setRange(0,maxSize);//进度条
QProcess *myProcess = new QProcess(this);
for(int i = 0;i<maxSize;i++)
{
QString filesStr;
for(int j=0;j<10;j++)
{
if((i*10+j) >= filePathes.size())
break;
QString onePath = filePathes.at(i*10+j);
onePath = onePath.replace(" ","\\ "); //将路径中的空格换成\加空格
filesStr = QString("%1 %2")
.arg(filesStr)
.arg(onePath);
}
QCoreApplication::processEvents();
QString cmd = QString("%1 %2 '%3 %4;%5 %6 %7%8'")
.arg("C:/cygwin/bin/bash.exe")
.arg("-lc")
.arg("cd")
.arg(rootPath)
.arg("tar.exe")
.arg("-uf")
.arg(tarName)
.arg(filesStr);
myProcess->start(cmd.toLocal8Bit().data());
if (!myProcess->waitForStarted())
{
std::cout << "启动失败\n";
// return false;
}
while (false == myProcess->waitForFinished())
{
if (myProcess->state() == QProcess::NotRunning) { //process failed
QMessageBox::critical(this, "Error", tr("Error when tar files."));
return;
//return false;
}
}
int exit= myProcess->exitCode();
if(exit!=0)
{
cout<<qPrintable(cmd)<<endl;
cout<<exit<<endl;
}
ui.progressBar->setValue(i+1);
}
ui.progressBar->setValue(0);
}