本文整理汇总了C++中QFile::exists方法的典型用法代码示例。如果您正苦于以下问题:C++ QFile::exists方法的具体用法?C++ QFile::exists怎么用?C++ QFile::exists使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类QFile
的用法示例。
在下文中一共展示了QFile::exists方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: Btn_onclicked
void Widget::Btn_onclicked()
{
// 创建文件操作对象
QFile *fp = new QFile("test.txt");
// 检查文件是否存在
if (!fp->exists()) {
QMessageBox::critical(this, "Error", fp->errorString());
return;
}
// 打开文件
if (!fp->open(QIODevice::ReadWrite|QIODevice::Text)) {
QMessageBox::critical(this, "Error", fp->errorString());
return;
}
// 使用文本流对文件进行操作
QTextStream out(fp);
//out.setCodec("UTF-8"); // 设置编码
QString text = out.readAll();
ui->textEdit->setText(text);
// 移动指针到末端并写入
//fp->seek(fp->size());
//out << "\r\n" << QString("321TEST");
// 关闭文件
fp->close();
delete fp;
// 设置textedit滚动到末端
QTextCursor cursor = ui->textEdit->textCursor();
cursor.movePosition(QTextCursor::End);
ui->textEdit->setTextCursor(cursor);
}
示例2: onExportButton_clicked
void DepExportDialog::onExportButton_clicked()
{
QString filename = QFileDialog::getSaveFileName( this, "Save file", "", ".csv");
if (filename.isNull())
return;
QFile *outputFile = new QFile(filename);
if (outputFile->exists()) {
if ( QMessageBox::question(this, tr("Export"), tr("Die Datei %1 existiert bereits.\nMöchten Sie sie überschreiben?").arg(filename),
QMessageBox::Yes, QMessageBox::No) == QMessageBox::No )
{
emit onExportButton_clicked();
return;
}
}
if (depExport(outputFile))
QMessageBox::information(0, QObject::tr("Export"), QObject::tr("DEP (DatenErfassungsProtokoll) wurde nach %1 exportiert.").arg(filename));
else
QMessageBox::warning(0, QObject::tr("Export"), QObject::tr("DEP (DatenErfassungsProtokoll) konnte nicht nach %1 exportiert werden.\nÜberprüfen Sie bitte Ihre Schreibberechtigung.").arg(filename));
this->close();
}
示例3: importFile
bool Model::importFile(const QFile& modelFile)
{
if(!modelFile.exists())
{
qDebug() << "Model::importFile(): import file" << modelFile.fileName() << "does not exist!";
return false;
}
mAssimpScene = mAssimpImporter.ReadFile(modelFile.fileName().toStdString(), aiProcessPreset_TargetRealtime_Quality);
// If the import failed, report it
if(!mAssimpScene)
{
qDebug() << "Model::importFile(): couldn't import file" << modelFile.fileName() << ":" << mAssimpImporter.GetErrorString();
return false;
}
else
{
// qDebug() << "Model::importFile(): successfully imported file" << modelFile.fileName();
}
// We're done. Everything will be cleaned up by the importer destructor
return true;
}
示例4: backupDatabase
bool Bookmark::backupDatabase( QString file_name )
{
configLS500 cfg ;
QString file_name_bk ;
if ( file_name.isEmpty() ) {
QString bk_path = cfg.getBookmarkDumpPath() ;
bk_path.replace( QRegExp( "(^\\$HOME)" ) , QDir::homePath() ) ;
bk_path += "." ;
bk_path += QDate::currentDate().toString( Qt::ISODate ) ;
bk_path += "-" ;
bk_path += QTime::currentTime().toString( Qt::ISODate ) ;
QFile file ;
int cnt = 1 ;
file_name_bk = bk_path ;
file.setFileName( file_name_bk );
while( file.exists() ) {
file_name_bk = bk_path + "." + "(" + QString().setNum(cnt++) + ")" ;
file.setFileName( file_name_bk );
}
}
QueryDB db ;
int rc = db.backup( cfg.getBookmarkPath() , file_name_bk ) ;
if ( rc == 0 )
return true ;
else
return false ;
}
示例5: getRequiredFilesFile
QFile* MainWindow::getRequiredFilesFile() {
QSettings settings;
//QString folder = settings.value("swg_folder").toString();
QFile* file = NULL;
//if (QDir(folder).exists()) {
file = new QFile("required2.txt");
if (file->exists()) {
if (file->open(QIODevice::ReadOnly | QIODevice::Text)) {
return file;
} else
delete file;
} else {
delete file;
}
//}
file = new QFile(":/files/required2.txt");
file->open(QIODevice::ReadOnly | QIODevice::Text);
return file;
}
示例6: deleteFile
void UIImageOverview::deleteFile(void) {
QFile f;
QString filename;
QString uri;
QString cacheFile;
filename = ui->listWidget->currentItem()->text();
if (filename != "") {
f.setFileName(filename);
if (f.exists()) {
f.remove();
ui->listWidget->takeItem(ui->listWidget->currentRow());
}
if (getUrlOfFilename(filename, &uri))
blackList->add(uri);
}
cacheFile = tnt->getCacheFile(filename);
emit removeFiles(QStringList(cacheFile));
}
示例7: test
QString KGrGameIO::getFilePath
(const QString & dir, const QString & prefix, const int level)
{
QString filePath = ((level == 0) ? "ende" : prefix);
filePath = dir + "game_" + filePath + ".txt";
QFile test (filePath);
// See if there is a game-file or "ENDE" screen in KGoldrunner 3 format.
if (test.exists()) {
return (filePath);
}
// If not, we are looking for a file in KGoldrunner 2 format.
if (level == 0) {
// End of game: show the "ENDE" screen.
filePath = dir + "levels/level000.grl";
}
else {
QString num = QString::number (level).rightJustified (3,'0');
filePath = dir + "levels/" + prefix + num + ".grl";
}
return (filePath);
}
示例8: init
void Session::init() {
qDebug() << "Loading sessions...";
QFile* configFile = new QFile ( Core::configurationPath().absolutePath() +"/sessions.xml" );
s_elems.clear();
if ( s_dom ) {
s_dom->clear();
delete s_dom;
}
s_dom = new QDomDocument ( "Sessions" );
if ( configFile->exists() ) {
configFile->open ( QIODevice::ReadOnly );
s_dom->setContent ( configFile );
const QDomElement documentElem = s_dom->documentElement();
const QDomNodeList l_domList = documentElem.elementsByTagName ( "Session" );
for ( int i = 0; i < l_domList.count(); i++ ) {
QDomElement l_node = l_domList.at ( i ).toElement();
const QUuid l_uuid ( l_node.attribute ( "uuid" ) );
s_elems.insert ( l_uuid, new QDomElement ( l_domList.at ( i ).toElement() ) );
}
qDebug() << l_domList.count() << "sessions loaded.";
} else {
configFile->open ( QIODevice::WriteOnly | QIODevice::Truncate );
QDomElement l_elem = s_dom->createElement ( "Sessions" );
s_dom->appendChild ( l_elem );
configFile->write ( s_dom->toString ( 4 ).toLocal8Bit() );
qDebug() << "Created session listing.";
}
configFile->close();
}
示例9: iconDir
QIconTheme::QIconTheme(const QString &themeName)
: m_valid(false)
{
QFile themeIndex;
QStringList iconDirs = QIcon::themeSearchPaths();
for ( int i = 0 ; i < iconDirs.size() ; ++i) {
QDir iconDir(iconDirs[i]);
QString themeDir = iconDir.path() + QLatin1Char('/') + themeName;
themeIndex.setFileName(themeDir + QLatin1String("/index.theme"));
if (themeIndex.exists()) {
m_contentDirs << themeDir;
m_valid = true;
QStringList themeSearchPaths = QIcon::themeSearchPaths();
foreach (QString path, themeSearchPaths)
{
if (!path.startsWith(':') && QFileInfo(path).isDir())
m_contentDirs.append(path + QLatin1Char('/') + themeName);
}
break;
}
}
示例10: loadfile
void MainWindow::loadfile(QString filename)
{
QSettings settings;
if(filename.isEmpty())
filename = QFileDialog::getOpenFileName(this, tr("Open..."), settings.value("LoadFile/lastDirectory", QDir::homePath()).toString(), tr("FUSE files (*.fuse *.xml)"));
if(filename.isEmpty())
return;
settings.setValue("LoadFile/lastDirectory", QFileInfo(filename).absolutePath());
QFile *file = new QFile(filename, this);
if(file->exists())
{
if (!file->open(QFile::ReadOnly | QFile::Text))
{
QMessageBox::critical(this, tr("Error!"), tr("Could not open file"));
return;
}
}
else
{
QMessageBox::critical(this, tr("Error!"), tr("No such file"));
return;
}
struct amp_settings amplifier_set;
struct fx_pedal_settings effects_set[4];
QString name;
LoadFromFile *loader = new LoadFromFile(file, &name, &lifier_set, effects_set);
loader->loadfile();
file->close();
delete loader;
delete file;
change_title(name);
amp->load(amplifier_set);
if(connected)
amp->send_amp();
if(settings.value("Settings/popupChangedWindows").toBool())
amp->show();
for(int i = 0; i < 4; i++)
{
switch(effects_set[i].fx_slot)
{
case 0x00:
effect1->load(effects_set[i]);
if(connected)
effect1->send_fx();
if(effects_set[i].effect_num)
if(settings.value("Settings/popupChangedWindows").toBool())
effect1->show();
break;
case 0x01:
effect2->load(effects_set[i]);
if(connected)
effect2->send_fx();
if(effects_set[i].effect_num)
if(settings.value("Settings/popupChangedWindows").toBool())
effect2->show();
break;
case 0x02:
effect3->load(effects_set[i]);
if(connected)
effect3->send_fx();
if(effects_set[i].effect_num)
if(settings.value("Settings/popupChangedWindows").toBool())
effect3->show();
break;
case 0x03:
effect4->load(effects_set[i]);
if(connected)
effect4->send_fx();
if(effects_set[i].effect_num)
if(settings.value("Settings/popupChangedWindows").toBool())
effect4->show();
break;
}
}
}
示例11: init
void QgsApplication::init( QString customConfigPath )
{
if ( customConfigPath.isEmpty() )
{
if ( getenv( "QGIS_CUSTOM_CONFIG_PATH" ) )
{
customConfigPath = getenv( "QGIS_CUSTOM_CONFIG_PATH" );
}
else
{
customConfigPath = QStringLiteral( "%1/.qgis3/" ).arg( QDir::homePath() );
}
}
qRegisterMetaType<QgsGeometry::Error>( "QgsGeometry::Error" );
qRegisterMetaType<QgsProcessingFeatureSourceDefinition>( "QgsProcessingFeatureSourceDefinition" );
qRegisterMetaType<QgsProcessingOutputLayerDefinition>( "QgsProcessingOutputLayerDefinition" );
QString prefixPath( getenv( "QGIS_PREFIX_PATH" ) ? getenv( "QGIS_PREFIX_PATH" ) : applicationDirPath() );
// QgsDebugMsg( QString( "prefixPath(): %1" ).arg( prefixPath ) );
// check if QGIS is run from build directory (not the install directory)
QFile f;
// "/../../.." is for Mac bundled app in build directory
Q_FOREACH ( const QString &path, QStringList() << "" << "/.." << "/bin" << "/../../.." )
{
f.setFileName( prefixPath + path + "/qgisbuildpath.txt" );
if ( f.exists() )
break;
}
if ( f.exists() && f.open( QIODevice::ReadOnly ) )
{
ABISYM( mRunningFromBuildDir ) = true;
ABISYM( mBuildSourcePath ) = f.readLine().trimmed();
ABISYM( mBuildOutputPath ) = f.readLine().trimmed();
qDebug( "Running from build directory!" );
qDebug( "- source directory: %s", ABISYM( mBuildSourcePath ).toUtf8().data() );
qDebug( "- output directory of the build: %s", ABISYM( mBuildOutputPath ).toUtf8().data() );
#ifdef _MSC_VER
ABISYM( mCfgIntDir ) = prefixPath.split( '/', QString::SkipEmptyParts ).last();
qDebug( "- cfg: %s", ABISYM( mCfgIntDir ).toUtf8().data() );
#endif
}
if ( ABISYM( mRunningFromBuildDir ) )
{
// we run from source directory - not installed to destination (specified prefix)
ABISYM( mPrefixPath ) = QString(); // set invalid path
#if defined(_MSC_VER) && !defined(USING_NMAKE) && !defined(USING_NINJA)
setPluginPath( ABISYM( mBuildOutputPath ) + '/' + QString( QGIS_PLUGIN_SUBDIR ) + '/' + ABISYM( mCfgIntDir ) );
#else
setPluginPath( ABISYM( mBuildOutputPath ) + '/' + QStringLiteral( QGIS_PLUGIN_SUBDIR ) );
#endif
setPkgDataPath( ABISYM( mBuildSourcePath ) ); // directly source path - used for: doc, resources, svg
ABISYM( mLibraryPath ) = ABISYM( mBuildOutputPath ) + '/' + QGIS_LIB_SUBDIR + '/';
#if defined(_MSC_VER) && !defined(USING_NMAKE) && !defined(USING_NINJA)
ABISYM( mLibexecPath ) = ABISYM( mBuildOutputPath ) + '/' + QGIS_LIBEXEC_SUBDIR + '/' + ABISYM( mCfgIntDir ) + '/';
#else
ABISYM( mLibexecPath ) = ABISYM( mBuildOutputPath ) + '/' + QGIS_LIBEXEC_SUBDIR + '/';
#endif
}
else
{
char *prefixPath = getenv( "QGIS_PREFIX_PATH" );
if ( !prefixPath )
{
#if defined(Q_OS_MACX) || defined(Q_OS_WIN)
setPrefixPath( applicationDirPath(), true );
#elif defined(ANDROID)
// this is "/data/data/org.qgis.qgis" in android
QDir myDir( QDir::homePath() );
myDir.cdUp();
QString myPrefix = myDir.absolutePath();
setPrefixPath( myPrefix, true );
#else
QDir myDir( applicationDirPath() );
myDir.cdUp();
QString myPrefix = myDir.absolutePath();
setPrefixPath( myPrefix, true );
#endif
}
else
{
setPrefixPath( prefixPath, true );
}
}
if ( !customConfigPath.isEmpty() )
{
ABISYM( mConfigPath ) = customConfigPath + '/'; // make sure trailing slash is included
}
ABISYM( mDefaultSvgPaths ) << qgisSettingsDirPath() + QStringLiteral( "svg/" );
ABISYM( mAuthDbDirPath ) = qgisSettingsDirPath();
if ( getenv( "QGIS_AUTH_DB_DIR_PATH" ) )
{
setAuthDatabaseDirPath( getenv( "QGIS_AUTH_DB_DIR_PATH" ) );
}
//.........这里部分代码省略.........
示例12: loadXml
bool plotsDialog::loadXml(bool init)
{
tabs->clear();
QFile file;
#ifdef Q_OS_WIN32
if(init)
{
QFile ofile(globalpara.caseName);
file.setFileName("plotTemp.xml");
if(file.exists())
file.remove();
if(!ofile.copy("plotTemp.xml"))
{
globalpara.reportError("Fail to generate temporary file for plots.",this);
return false;
}
else file.setFileName("plotTemp.xml");
}
else file.setFileName("plotTemp.xml");
#endif
#ifdef Q_OS_MAC
QDir dir = qApp->applicationDirPath();
/*dir.cdUp();*/
/*dir.cdUp();*/
/*dir.cdUp();*/
QString bundleDir(dir.absolutePath());
if(init)
{
QFile ofile(globalpara.caseName);
file.setFileName(bundleDir+"/plotTemp.xml");
if(file.exists())
file.remove();
if(!ofile.copy(bundleDir+"/plotTemp.xml"))
{
globalpara.reportError("Fail to generate temporary file for plots.",this);
return false;
}
else file.setFileName(bundleDir+"/plotTemp.xml");
}
else file.setFileName(bundleDir+"/plotTemp.xml");
#endif
QDomDocument doc;
QDomElement plotData, currentPlot;
int plotCount=0;
Plot*newPlot;
if(!file.open(QIODevice::ReadOnly | QIODevice::Text))
{
globalpara.reportError("Fail to open the xml file for plots!",this);
return false;
}
else
{
if(!doc.setContent(&file))
{
globalpara.reportError("Fail to set DomDoc to file content when loading xml file for plots!",this);
file.close();
return false;
}
else
{
if(doc.elementsByTagName("plotData").count()==0)
{
globalpara.reportError("Error! There is no <plotData> branch in the case xml file!",this);
file.close();
return false;
}
else
plotData = doc.elementsByTagName("plotData").at(0).toElement();
plotCount = plotData.childNodes().count();
for(int i = 0; i < plotCount; i++)
{
currentPlot = plotData.childNodes().at(i).toElement();
if(currentPlot.attribute("plotType")=="parametric")
{
QDomElement currentRun,runInput,runOutput;
double currentInput;
int axis_info[8];
QStringList currentOutput, xValues, axis_name, info;
QMultiMap<double,double> allData;
axis_name.append(currentPlot.attribute("xAxisName"));
axis_name= axis_name + currentPlot.attribute("yAxisName").split(",");
info = currentPlot.attribute("scaleInfo").split(",");
for(int j = 0; j < 8; j++)
axis_info[j] = info.at(j).toInt();
int nRuns = currentPlot.elementsByTagName("Run").count(), nOutputs = currentPlot.attribute("outputs").toInt();
for(int j = 0; j < nRuns; j++)
{
currentOutput.clear();
currentRun = currentPlot.elementsByTagName("Run").at(j).toElement();
runInput = currentRun.elementsByTagName("Input").at(0).toElement();
currentInput = runInput.elementsByTagName("value").at(0).toElement().text().toDouble();
xValues.append(QString::number(currentInput));
for(int p = 0; p < nOutputs; p++)
{
runOutput = currentRun.elementsByTagName("Output").at(p).toElement();
currentOutput.append(runOutput.elementsByTagName("value").at(0).toElement().text());
allData.insert(currentInput,currentOutput.at(p).toDouble());
}
//.........这里部分代码省略.........
示例13: invoiceInsertData
bool XmlDataLayer::invoiceInsertData(InvoiceData& oi_invData, int type) {
qDebug() << __FILE__ << __LINE__ << __FUNCTION__;
QDomDocument doc(sett().getInoiveDocName());
QDomElement root;
QString fileName = oi_invData.id;
QFile file;
if (fileName == "") {
fileName = QDate::currentDate().toString(sett().getFnameDateFormat());
int pNumber = 0;
file.setFileName(sett().getInvoicesDir() + "h" + fileName + "_"
+ sett().numberToString(pNumber) + ".xml");
oi_invData.id = "h" + fileName + "_" + sett().numberToString(pNumber) + ".xml";
pNumber += 1;
while (file.exists()) {
file.setFileName(sett().getInvoicesDir() + "h" + fileName + "_"
+ sett().numberToString(pNumber) + ".xml");
oi_invData.id = "h" + fileName + "_" + sett().numberToString(pNumber) + ".xml";
pNumber += 1;
}
// fName = "h" + fileName + "_" + sett().numberToString(pNumber) + ".xml";
} else {
file.setFileName(sett().getInvoicesDir() + fileName);
oi_invData.id = fileName + "|";
}
// if (!file.open (QIODevice::ReadOnly)) {
root = doc.createElement("invoice");
root.setAttribute("no", oi_invData.frNr);
oi_invData.issueDate = QDate::currentDate();
root.setAttribute("issueDate", oi_invData.issueDate.toString(sett().getDateFormat()));
root.setAttribute("sellingDate", oi_invData.sellingDate.toString(sett().getDateFormat()));
QString invType = oi_invData.getInvoiceTypeAndSaveNr(type);
root.setAttribute("type", invType);
doc.appendChild(root);
QDomElement sprzedawca = doc.createElement("seller");
invoiceSellerDataToElem(oi_invData, sprzedawca);
root.appendChild(sprzedawca);
QDomElement nabywca = doc.createElement("buyer");
invoiceBuyerDataToElem(oi_invData, nabywca);
root.appendChild(nabywca);
QDomElement product;
QDomElement products;
products = doc.createElement("products");
products.setAttribute("discount", sett().numberToString(oi_invData.discount));
QMap<int, ProductData>::const_iterator i = oi_invData.products.constBegin();
int abc = 0;
while (i != oi_invData.products.constEnd()) {
product = doc.createElement("product");
// ProductData pr = i.value();
invoiceProdDataToElem(i.value(), product);
products.appendChild(product);
i++;
}
root.appendChild(products);
QDomElement addinfo;
addinfo = doc.createElement("addinfo");
addinfo.setAttribute("text", oi_invData.additText);
addinfo.setAttribute("paymentType", oi_invData.paymentType );
addinfo.setAttribute("liabDate", oi_invData.liabDate.toString(sett().getDateFormat()));
addinfo.setAttribute("currency", oi_invData.currencyType);
/*
if (platCombo->currentIndex() == sett().value("payments").toString().split("|").count() - 1) {
addinfo.setAttribute("payment1", custPaymData->payment1);
addinfo.setAttribute("amount1", sett().numberToString(custPaymData->amount1, 'f', 2));
addinfo.setAttribute("liabDate1", custPaymData->date1.toString(
sett().getDateFormat()));
addinfo.setAttribute("payment2", custPaymData->payment2);
addinfo.setAttribute("amount2", sett().numberToString(custPaymData->amount2, 'f', 2));
addinfo.setAttribute("liabDate2", custPaymData->date2.toString(
sett().getDateFormat()));
}
*/
root.appendChild(addinfo);
QString xml = doc.toString();
file.close();
if (!file.open(QIODevice::WriteOnly)) {
// saveFailed = true;
return false;
}
QTextStream ts(&file);
ts << xml;
file.close();
//.........这里部分代码省略.........
示例14: readSTL
/** Anm. JH
* Hier wird das Graphik-Modell geladen?
* @brief Methode zum einbinden der STL-Dateien
*/
int readSTL(QVector <triangle> *triangleList, QString path)
{
int triCount = 0;
int strIndex = 0;
QFile file (path);
QTextStream stream(&file);
QString line, strX, strY, strZ, value;
GLfloat tempPoints[3][3] = {{0.0,0.0,0.0},{0.0,0.0,0.0},{0.0,0.0,0.0}};
triangle tri;
strX = ""; strY = ""; strZ = "";
value = "0123456789+-.e";
if(!file.exists())
{
qDebug()<< "STL-Datei"<<path<<"existiert nicht! Ende.";
assert(false);
}
file.open(QIODevice::ReadOnly);
while(!stream.atEnd())
{
line = stream.readLine();
if(line.contains("outer loop") && triCount != 0)
return RETURN_OK;
else if(line.contains("endloop") && triCount != 3)
return RETURN_ERROR;
else if(line.contains("endloop") && triCount == 3)
{
triCount = 0;
memmove(tri.vertex0, tempPoints[0], sizeof(tempPoints[0]));
memmove(tri.vertex1, tempPoints[1], sizeof(tempPoints[0]));
memmove(tri.vertex2, tempPoints[2], sizeof(tempPoints[0]));
getNormal(tri.normal, tri.vertex0, tri.vertex1, tri.vertex2);
(*triangleList).push_back(tri);
}
else if((strIndex = line.lastIndexOf("vertex",-1)) != -1)
{
strIndex+=7;
while(value.contains(line[strIndex]))
{
strX+=line[strIndex];
strIndex++;
};
strIndex++;
while(value.contains(line[strIndex]))
{
strY+=line[strIndex];
strIndex++;
};
strIndex++;
while(value.contains(line[strIndex]))
{
strZ+=line[strIndex];
strIndex++;
};
tempPoints[triCount][0] = strX.toDouble();
tempPoints[triCount][1] = strY.toDouble();
tempPoints[triCount][2] = strZ.toDouble();
strX.clear();
strY.clear();
strZ.clear();
triCount++;
}
};
file.close(); // Datei wieder schließen
return RETURN_OK;
}
示例15: extractFileToTargetFolder
/*! \brief Extracts the selected .tar.gz archive to the selected folder, will try to create the target folder if it does not exist.
* @param filePath Full path to selected archive.
* @param targetFolderPath Full path to target folder.
* @return Returns full path to the extracted archive, or empty QString if failed.
*/
QString ArchiveExtractor::extractFileToTargetFolder(QString filePath, QString targetFolderPath){
//check if the selected archive file exist
QFile *selectedFile = new QFile(filePath);
if(!selectedFile->exists()){
qDebug()<<"ERROR: File marked for decompression does not exist!";
delete selectedFile;
return QString("");
}
delete selectedFile;
struct archive *a;
struct archive *ext;
struct archive_entry *entry;
int r;
// /* The "flags" argument selects optional behavior, 'OR' the flags you want. */
// /* Default: Do not try to set owner/group. */
//#define ARCHIVE_EXTRACT_OWNER (0x0001)
// /* Default: Do obey umask, do not restore SUID/SGID/SVTX bits. */
//#define ARCHIVE_EXTRACT_PERM (0x0002)
// /* Default: Do not restore mtime/atime. */
//#define ARCHIVE_EXTRACT_TIME (0x0004)
// /* Default: Replace existing files. */
//#define ARCHIVE_EXTRACT_NO_OVERWRITE (0x0008)
// /* Default: Try create first, unlink only if create fails with EEXIST. */
//#define ARCHIVE_EXTRACT_UNLINK (0x0010)
// /* Default: Do not restore ACLs. */
//#define ARCHIVE_EXTRACT_ACL (0x0020)
// /* Default: Do not restore fflags. */
//#define ARCHIVE_EXTRACT_FFLAGS (0x0040)
// /* Default: Do not restore xattrs. */
//#define ARCHIVE_EXTRACT_XATTR (0x0080)
// /* Default: Do not try to guard against extracts redirected by symlinks. */
// /* Note: With ARCHIVE_EXTRACT_UNLINK, will remove any intermediate symlink. */
//#define ARCHIVE_EXTRACT_SECURE_SYMLINKS (0x0100)
// /* Default: Do not reject entries with '..' as path elements. */
//#define ARCHIVE_EXTRACT_SECURE_NODOTDOT (0x0200)
// /* Default: Create parent directories as needed. */
//#define ARCHIVE_EXTRACT_NO_AUTODIR (0x0400)
// /* Default: Overwrite files, even if one on disk is newer. */
//#define ARCHIVE_EXTRACT_NO_OVERWRITE_NEWER (0x0800)
// /* Detect blocks of 0 and write holes instead. */
//#define ARCHIVE_EXTRACT_SPARSE (0x1000)
// /* Default: Do not restore Mac extended metadata. */
// /* This has no effect except on Mac OS. */
//#define ARCHIVE_EXTRACT_MAC_METADATA (0x2000)
int flags = 0;
// flags |= ARCHIVE_EXTRACT_TIME;
// flags |= ARCHIVE_EXTRACT_NO_AUTODIR;
// flags |= ARCHIVE_EXTRACT_NO_OVERWRITE_NEWER;
QFileInfo *fileInfo = new QFileInfo(filePath);
// qDebug()<<"resolved filename: "<<fileInfo->fileName();
delete fileInfo;
//MEMORY LEAK!!! (Pointers be dangerous, man. :)
// const char *filename = fileInfo->fileName().toUtf8().constData();
//AVOID IT BY CONVERTING TO A QBYTEARRAY FIRST!
QByteArray byteArray = filePath.toUtf8();
const char *filename = byteArray.constData();
//That's better :D
//toggle extraction
bool do_extract = true;
a = archive_read_new();
ext = archive_write_disk_new();
archive_write_disk_set_options(ext, flags);
//tuned for .tar.gz
archive_read_support_filter_gzip(a);
archive_read_support_format_gnutar(a);
if((r = archive_read_open_filename(a, filename, 10240)) ){
errmsg(archive_error_string(a));
}
for(;;){
r = archive_read_next_header(a, &entry);
if(r == ARCHIVE_EOF) break;
if(r != ARCHIVE_OK){
errmsg(archive_error_string(a));
}
if (verbose || !do_extract){
qDebug()<<"Detected files in archive: ";
msg(archive_entry_pathname(entry));
}
QString currentPath(archive_entry_pathname( entry ));
qDebug()<<currentPath;
QDir targetFolder(targetFolderPath);
if(!targetFolder.exists()){//target folder does not exist
//attempt to create it
if(!targetFolder.mkpath(targetFolderPath)){//failed to create target folder
//break procedure
qDebug()<<"ERROR: Target folder does not exist and cannot be created";
return QString("");
}
//.........这里部分代码省略.........