当前位置: 首页>>代码示例>>C++>>正文


C++ QTemporaryFile::errorString方法代码示例

本文整理汇总了C++中QTemporaryFile::errorString方法的典型用法代码示例。如果您正苦于以下问题:C++ QTemporaryFile::errorString方法的具体用法?C++ QTemporaryFile::errorString怎么用?C++ QTemporaryFile::errorString使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在QTemporaryFile的用法示例。


在下文中一共展示了QTemporaryFile::errorString方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。

示例1: cook

void Oven::cook(QString inputContents, QString scriptContents) {
  QTemporaryFile file;
  QProcess process;
  
  if (file.open()) {
    QString filename = file.fileName();
    
    file.write(scriptContents.toUtf8());
    if (!file.error()) {
      file.close();
      
      process.setProcessChannelMode(QProcess::ForwardedChannels);
      process.start("bash", QStringList() << filename);
      
      QTextStream inputStream(&process);
      inputStream << inputContents;
      inputStream.flush();
      process.closeWriteChannel();
      
      if (process.waitForStarted() && process.waitForFinished()) {
        // success!
        return;
      }
    }
  }
  
  if (file.error() != QTemporaryFile::NoError) {
    emit error(file.errorString());
  } else {
    emit error(process.errorString());
  }
  
  // error.
  return;
}
开发者ID:gelisam,项目名称:Substrate,代码行数:35,代码来源:Oven.cpp

示例2: runner

ProcessPtr
Process::execute(QString const &command,
                 QStringList const &args,
                 bool useTempFile) {
  auto runner = [](QString const &commandToUse, QStringList const &argsToUse) {
    auto pr = std::make_shared<Process>( commandToUse, argsToUse );
    pr->run();
    return pr;
  };

  if (!useTempFile)
    return runner(command, args);

  QTemporaryFile optFile;

  if (!optFile.open())
    throw ProcessX{ to_utf8(QY("Error creating a temporary file (reason: %1).").arg(optFile.errorString())) };

  static const unsigned char utf8_bom[3] = {0xef, 0xbb, 0xbf};
  optFile.write(reinterpret_cast<char const *>(utf8_bom), 3);
  for (auto &arg : args)
    optFile.write(QString{"%1\n"}.arg(arg).toUtf8());
  optFile.close();

  QStringList argsToUse;
  argsToUse << QString{"@%1"}.arg(optFile.fileName());
  return runner(command, argsToUse);
}
开发者ID:CharlesLio,项目名称:mkvtoolnix,代码行数:28,代码来源:process.cpp

示例3: lock

bool MountProtector::lock(const QString& path) {
    if (path.isEmpty()) {
        qmlInfo(this) << "Cannot lock an empty path";
        return false;
    }

    QString p = QString("%1%2.cameraplus_tmp_XXXXXX").arg(path).arg(QDir::separator());
    QTemporaryFile *file = new QTemporaryFile(p);
    file->setAutoRemove(true);

    if (!file->open()) {
        qmlInfo(this) << "Failed to lock" << file->errorString();
        delete file;
        file = 0;
        return false;
    }

    if (!QFile::remove(file->fileName())) {
        qmlInfo(this) << "Failed to remove temporarily file" << file->fileName();
    }

    m_locks.insert(path, file);

    return true;
}
开发者ID:ballock,项目名称:cameraplus,代码行数:25,代码来源:mountprotector.cpp

示例4: ouvrirCSV

void SqlTableModel::ouvrirCSV(QString commande)
{
    QTemporaryFile* temporaryFile = new QTemporaryFile(parent());
    if (temporaryFile->open()) {
        QxtCsvModel csv(this);
        csv.insertColumns(0, columnCount());
        csv.insertRows(0, rowCount());
        for (int column = 0; column < csv.columnCount(); column ++) {
            csv.setHeaderText(column, headerData(column, Qt::Horizontal).toString());
        }
        for (int row = 0; row < csv.rowCount(); row ++) {
            for (int column = 0; column < csv.columnCount(); column ++) {
                csv.setText(row, column, QSqlTableModel::data(index(row, column)).toString());
            }
        }
        csv.toCSV(temporaryFile->fileName(), true);
        temporaryFile->close();
        QProcess* process = new QProcess();
        process->start(commande, QStringList { temporaryFile->fileName() });
        connect(process, SIGNAL(finished(int)), temporaryFile, SLOT(deleteLater()));
    } else {
        qCritical() << temporaryFile->errorString();
    }

}
开发者ID:sebastiendu,项目名称:gestionnairedaffectations,代码行数:25,代码来源:sqltablemodel.cpp

示例5: getReport

QFileInfoList CDspHaClusterHelper::getReport()
{
	QFileInfoList output;
	QFileInfo p("/usr/bin/vstorage-make-report");
	if (!p.exists())
		return output;
	QDir d("/etc/vstorage/clusters");
	if (!d.exists())
		return output;
	QStringList a = d.entryList(QDir::NoDotAndDotDot | QDir::Dirs);
	foreach (QString x, a)
	{
		QTemporaryFile t;
		t.setFileTemplate(QString("%1/pstorage.%2.XXXXXX.tgz")
			.arg(QDir::tempPath()).arg(x));
		if (!t.open())
		{
			WRITE_TRACE(DBG_FATAL, "QTemporaryFile::open() error: %s",
					QSTR2UTF8(t.errorString()));
			continue;
		}
		QString b, c = QString("%1 -f %2 \"%3\"").arg(p.filePath()).arg(t.fileName()).arg(x);
		if (!HostUtils::RunCmdLineUtility(c, b, -1) || t.size() == 0)
		{
			t.close();
			continue;
		}
		t.setAutoRemove(false);
		output.append(QFileInfo(t.fileName()));
		t.close();
	}
开发者ID:OpenVZ,项目名称:prl-disp-service,代码行数:31,代码来源:CDspHaClusterHelper.cpp

示例6: initialize

bool StateOrchestrator::initialize()
{
    bool ret = false;

    if (isSaving()) {

        QFileInfo fi(fileName);
        QTemporaryFile *tfile = new(std::nothrow) QTemporaryFile(fi.absolutePath().append(QDir::separator()));
        file = tfile;

        if (tfile == nullptr) {
            qFatal("Cannot allocate memory for QTemporaryFile X{");
        }

        ret = tfile->open();
        if (!ret) {
            emit log(tr("Cannot open temporary state file for saving: %1").arg(tfile->errorString()),metaObject()->className(), Pip3lineConst::LERROR);
            return false;
        }
        writer = new(std::nothrow) QXmlStreamWriter(tfile);

        if (writer == nullptr) {
            qFatal("Cannot allocate memory for QXmlStreamWriter X{");
        }

        writer->writeStartDocument();
        writer->writeStartElement(GuiConst::STATE_PIP3LINE_DOC);

    } else {
        file = new(std::nothrow) QFile(fileName); // file is automatically deleted when the orchestrator is deleted
        if (file == nullptr) {
            qFatal("Cannot allocate memory for QFile X{");
        }

        ret = file->open(QIODevice::ReadOnly);
        if (!ret) {
            emit log(tr("Cannot open state file for loading: %1").arg(file->errorString()),metaObject()->className(), Pip3lineConst::LERROR);
            return false;
        }
        reader = new(std::nothrow) QXmlStreamReader(file);

        if (reader == nullptr) {
            qFatal("Cannot allocate memory for QXmlStreamReader X{");
        }

        if (!reader->readNextStartElement()) {
            emit log(tr("XML document seems empty"),metaObject()->className(), Pip3lineConst::LERROR);
            return false;
        } else if (reader->name() != GuiConst::STATE_PIP3LINE_DOC) {
            emit log(tr("This is not a Pip3line state document (%1)").arg(reader->name().toString()),metaObject()->className(), Pip3lineConst::LERROR);
            return false;
        }
    }

    return true;
}
开发者ID:pipacker10,项目名称:pip3line,代码行数:56,代码来源:stateorchestrator.cpp

示例7: openAttachment

void EditEntryWidget::openAttachment(const QModelIndex& index)
{
    if (!index.isValid()) {
        Q_ASSERT(false);
        return;
    }

    QString filename = m_attachmentsModel->keyByIndex(index);
    QByteArray attachmentData = m_entryAttachments->value(filename);

    // tmp file will be removed once the database (or the application) has been closed
    QString tmpFileTemplate = QDir::temp().absoluteFilePath(QString("XXXXXX.").append(filename));
    QTemporaryFile* file = new QTemporaryFile(tmpFileTemplate, this);

    if (!file->open()) {
        MessageBox::warning(this, tr("Error"),
                tr("Unable to save the attachment:\n").append(file->errorString()));
        return;
    }

    if (file->write(attachmentData) != attachmentData.size()) {
        MessageBox::warning(this, tr("Error"),
                tr("Unable to save the attachment:\n").append(file->errorString()));
        return;
    }

    if (!file->flush()) {
        MessageBox::warning(this, tr("Error"),
                tr("Unable to save the attachment:\n").append(file->errorString()));
        return;
    }

    file->close();

    QDesktopServices::openUrl(QUrl::fromLocalFile(file->fileName()));
}
开发者ID:jrodan,项目名称:keepassx,代码行数:36,代码来源:EditEntryWidget.cpp

示例8: CreateEncryptionXML

void ExportEPUB::CreateEncryptionXML(const QString &fullfolderpath)
{
    QTemporaryFile file;

    if (!file.open()) {
        boost_throw(CannotOpenFile()
                    << errinfo_file_fullpath(file.fileName().toStdString())
                    << errinfo_file_errorstring(file.errorString().toStdString())
                   );
    }

    EncryptionXmlWriter enc(*m_Book, file);
    enc.WriteXML();
    // Write to disk immediately
    file.flush();
    QFile::copy(file.fileName(), fullfolderpath + "/" + ENCRYPTION_XML_FILE_NAME);
}
开发者ID:marek-g,项目名称:Sigil,代码行数:17,代码来源:ExportEPUB.cpp

示例9: listen

bool FiFoTty::listen()
{
    if (!m_serverPath.isEmpty())
        return true;
    if (!m_serverPath.isEmpty())
        return true;
    QByteArray codedServerPath;
    forever {
        {
            QTemporaryFile tf;
            if (!tf.open()) {
                m_errorString = tr("Cannot create temporary file: %1").arg(tf.errorString());
                m_serverPath.clear();
                return false;
            }
            m_serverPath = tf.fileName();
        }
        // By now the temp file was deleted again
        codedServerPath = QFile::encodeName(m_serverPath);
        if (!::mkfifo(codedServerPath.constData(), 0600))
            break;
        if (errno != EEXIST) {
            m_errorString = tr("Cannot create FiFo %1: %2").
                            arg(m_serverPath, QString::fromLocal8Bit(strerror(errno)));
            m_serverPath.clear();
            return false;
        }
    }
    if ((m_serverFd = ::open(codedServerPath.constData(), O_RDWR|O_NONBLOCK)) < 0) {
        m_errorString = tr("Cannot open FiFo %1: %2").
                        arg(m_serverPath, QString::fromLocal8Bit(strerror(errno)));
        m_serverPath.clear();
        return false;
    }
    m_serverNotifier = new QSocketNotifier(m_serverFd, QSocketNotifier::Read, this);
    connect(m_serverNotifier, SIGNAL(activated(int)), SLOT(bytesAvailable()));
    return true;
}
开发者ID:peidachang,项目名称:liteide,代码行数:38,代码来源:fifotty.cpp

示例10: assemble

static int assemble(Input input, const QInstaller::Settings &settings, const QString &signingIdentity)
{
#ifdef Q_OS_OSX
    if (QInstaller::isInBundle(input.installerExePath)) {
        const QString bundle = input.installerExePath;
        // if the input file was a bundle
        const QSettings s(QString::fromLatin1("%1/Contents/Info.plist").arg(input.installerExePath),
            QSettings::NativeFormat);
        input.installerExePath = QString::fromLatin1("%1/Contents/MacOS/%2").arg(bundle)
            .arg(s.value(QLatin1String("CFBundleExecutable"),
            QFileInfo(input.installerExePath).completeBaseName()).toString());
    }

    const bool createDMG = input.outputPath.endsWith(QLatin1String(".dmg"));
    if (createDMG)
        input.outputPath.replace(input.outputPath.length() - 4, 4, QLatin1String(".app"));

    const bool isBundle = input.outputPath.endsWith(QLatin1String(".app"));
    const QString bundle = isBundle ? input.outputPath : QString();
    const BundleBackup bundleBackup(bundle);

    if (isBundle) {
        // output should be a bundle
        const QFileInfo fi(input.outputPath);

        const QString contentsResourcesPath = fi.filePath() + QLatin1String("/Contents/Resources/");

        QInstaller::mkpath(fi.filePath() + QLatin1String("/Contents/MacOS"));
        QInstaller::mkpath(contentsResourcesPath);

        {
            QFile pkgInfo(fi.filePath() + QLatin1String("/Contents/PkgInfo"));
            pkgInfo.open(QIODevice::WriteOnly);
            QTextStream pkgInfoStream(&pkgInfo);
            pkgInfoStream << QLatin1String("APPL????") << endl;
        }

        QString iconFile;
        if (QFile::exists(settings.installerApplicationIcon())) {
            iconFile = settings.installerApplicationIcon();
        } else {
            iconFile = QString::fromLatin1(":/resources/default_icon_mac.icns");
        }

        const QString iconTargetFile = fi.completeBaseName() + QLatin1String(".icns");
        QFile::copy(iconFile, contentsResourcesPath + iconTargetFile);
        if (QDir(qApp->applicationDirPath() + QLatin1String("/qt_menu.nib")).exists()) {
            copyDirectoryContents(qApp->applicationDirPath() + QLatin1String("/qt_menu.nib"),
                contentsResourcesPath + QLatin1String("/qt_menu.nib"));
        }

        QFile infoPList(fi.filePath() + QLatin1String("/Contents/Info.plist"));
        infoPList.open(QIODevice::WriteOnly);
        QTextStream plistStream(&infoPList);
        plistStream << QLatin1String("<?xml version=\"1.0\" encoding=\"UTF-8\"?>") << endl;
        plistStream << QLatin1String("<!DOCTYPE plist SYSTEM \"file://localhost/System/Library/DTDs"
            "/PropertyList.dtd\">") << endl;
        plistStream << QLatin1String("<plist version=\"0.9\">") << endl;
        plistStream << QLatin1String("<dict>") << endl;
        plistStream << QLatin1String("    <key>CFBundleIconFile</key>") << endl;
        plistStream << QLatin1String("    <string>") << iconTargetFile << QLatin1String("</string>")
            << endl;
        plistStream << QLatin1String("    <key>CFBundlePackageType</key>") << endl;
        plistStream << QLatin1String("    <string>APPL</string>") << endl;
        plistStream << QLatin1String("    <key>CFBundleGetInfoString</key>") << endl;
#define QUOTE_(x) #x
#define QUOTE(x) QUOTE_(x)
        plistStream << QLatin1String("    <string>") << QLatin1String(QUOTE(IFW_VERSION_STR)) << ("</string>")
            << endl;
#undef QUOTE
#undef QUOTE_
        plistStream << QLatin1String("    <key>CFBundleSignature</key>") << endl;
        plistStream << QLatin1String("    <string> ???? </string>") << endl;
        plistStream << QLatin1String("    <key>CFBundleExecutable</key>") << endl;
        plistStream << QLatin1String("    <string>") << fi.completeBaseName() << QLatin1String("</string>")
            << endl;
        plistStream << QLatin1String("    <key>CFBundleIdentifier</key>") << endl;
        plistStream << QLatin1String("    <string>com.yourcompany.installerbase</string>") << endl;
        plistStream << QLatin1String("    <key>NOTE</key>") << endl;
        plistStream << QLatin1String("    <string>This file was generated by Qt Installer Framework.</string>")
            << endl;
        plistStream << QLatin1String("    <key>NSPrincipalClass</key>") << endl;
        plistStream << QLatin1String("    <string>NSApplication</string>") << endl;
        plistStream << QLatin1String("</dict>") << endl;
        plistStream << QLatin1String("</plist>") << endl;

        input.outputPath = QString::fromLatin1("%1/Contents/MacOS/%2").arg(input.outputPath)
            .arg(fi.completeBaseName());
    }
#elif defined(Q_OS_LINUX)
    Q_UNUSED(settings)
#endif

    QTemporaryFile file(input.outputPath);
    if (!file.open()) {
        throw Error(QString::fromLatin1("Cannot copy %1 to %2: %3").arg(input.installerExePath,
            input.outputPath, file.errorString()));
    }

    const QString tempFile = file.fileName();
//.........这里部分代码省略.........
开发者ID:,项目名称:,代码行数:101,代码来源:

示例11: save

void HistoryManager::save()
{
    QSettings settings;
    settings.beginGroup(QLatin1String("history"));
    settings.setValue(QLatin1String("historyLimit"), m_historyLimit);

    bool saveAll = m_lastSavedUrl.isEmpty();
    int first = m_history.count() - 1;
    if (!saveAll) {
        // find the first one to save
        for (int i = 0; i < m_history.count(); ++i) {
            if (m_history.at(i).url == m_lastSavedUrl) {
                first = i - 1;
                break;
            }
        }
    }
    if (first == m_history.count() - 1)
        saveAll = true;

    QString directory = QStandardPaths::writableLocation(QStandardPaths::DataLocation);
    if (directory.isEmpty())
        directory = QDir::homePath() + QLatin1String("/.") + QCoreApplication::applicationName();
    if (!QFile::exists(directory)) {
        QDir dir;
        dir.mkpath(directory);
    }

    QFile historyFile(directory + QLatin1String("/history"));
    // When saving everything use a temporary file to prevent possible data loss.
    QTemporaryFile tempFile;
    tempFile.setAutoRemove(false);
    bool open = false;
    if (saveAll) {
        open = tempFile.open();
    } else {
        open = historyFile.open(QFile::Append);
    }

    if (!open) {
        qWarning() << "Unable to open history file for saving"
                   << (saveAll ? tempFile.fileName() : historyFile.fileName());
        return;
    }

    QDataStream out(saveAll ? &tempFile : &historyFile);
    for (int i = first; i >= 0; --i) {
        QByteArray data;
        QDataStream stream(&data, QIODevice::WriteOnly);
        HistoryItem item = m_history.at(i);
        stream << HISTORY_VERSION << item.url << item.dateTime << item.title;
        out << data;
    }
    tempFile.close();

    if (saveAll) {
        if (historyFile.exists() && !historyFile.remove())
            qWarning() << "History: error removing old history." << historyFile.errorString();
        if (!tempFile.rename(historyFile.fileName()))
            qWarning() << "History: error moving new history over old." << tempFile.errorString() << historyFile.fileName();
    }
    m_lastSavedUrl = m_history.value(0).url;
}
开发者ID:Metrological,项目名称:qtwebengine,代码行数:63,代码来源:history.cpp

示例12: save

/**
 * Save the database to a file.
 *
 * This function uses QTemporaryFile instead of QSaveFile due to a bug
 * in Qt (https://bugreports.qt.io/browse/QTBUG-57299) that may prevent
 * the QSaveFile from renaming itself when using Dropbox, Drive, or OneDrive.
 *
 * The risk in using QTemporaryFile is that the rename function is not atomic
 * and may result in loss of data if there is a crash or power loss at the
 * wrong moment.
 *
 * @param filePath Absolute path of the file to save
 * @param atomic Use atomic file transactions
 * @param backup Backup the existing database file, if exists
 * @param error error message in case of failure
 * @return true on success
 */
bool Database::save(const QString& filePath, QString* error, bool atomic, bool backup)
{
    Q_ASSERT(!m_data.isReadOnly);
    if (m_data.isReadOnly) {
        return false;
    }

    if (atomic) {
        QSaveFile saveFile(filePath);
        if (saveFile.open(QIODevice::WriteOnly)) {
            // write the database to the file
            if (!writeDatabase(&saveFile, error)) {
                return false;
            }

            if (backup) {
                backupDatabase(filePath);
            }

            if (saveFile.commit()) {
                // successfully saved database file
                setFilePath(filePath);
                return true;
            }
        }

        if (error) {
            *error = saveFile.errorString();
        }
    } else {
        QTemporaryFile tempFile;
        if (tempFile.open()) {
            // write the database to the file
            if (!writeDatabase(&tempFile, error)) {
                return false;
            }

            tempFile.close(); // flush to disk

            if (backup) {
                backupDatabase(filePath);
            }

            // Delete the original db and move the temp file in place
            QFile::remove(filePath);

            // Note: call into the QFile rename instead of QTemporaryFile
            // due to an undocumented difference in how the function handles
            // errors. This prevents errors when saving across file systems.
            if (tempFile.QFile::rename(filePath)) {
                // successfully saved the database
                tempFile.setAutoRemove(false);
                setFilePath(filePath);
                return true;
            } else if (!backup || !restoreDatabase(filePath)) {
                // Failed to copy new database in place, and
                // failed to restore from backup or backups disabled
                tempFile.setAutoRemove(false);
                if (error) {
                    *error = tr("%1\nBackup database located at %2").arg(tempFile.errorString(), tempFile.fileName());
                }
                markAsModified();
                return false;
            }
        }

        if (error) {
            *error = tempFile.errorString();
        }
    }

    // Saving failed
    markAsModified();
    return false;
}
开发者ID:droidmonkey,项目名称:keepassx_http,代码行数:92,代码来源:Database.cpp

示例13: loadResource

QVariant EpubDocument::loadResource(int type, const QUrl &name)
{
  int size;
  char *data;

  QString fileInPath = mCurrentSubDocument.resolved(name).path();

  // Get the data from the epub file
  size = epub_get_data(mEpub, fileInPath.toUtf8().constData(), &data);

  QVariant resource;

  if (data) {
    switch(type) {
    case QTextDocument::ImageResource:{
      QImage img = QImage::fromData((unsigned char *)data, size);
      const int maxHeight = maxContentHeight();
      const int maxWidth = maxContentWidth();
      if(img.height() > maxHeight)
        img = img.scaledToHeight(maxHeight);
      if(img.width() > maxWidth)
        img = img.scaledToWidth(maxWidth);
      resource.setValue(img);
      break;
    }
    case QTextDocument::StyleSheetResource: {
      QString css = QString::fromUtf8(data);
      checkCSS(css);
      resource.setValue(css);
      break;
    }
    case EpubDocument::MovieResource: {
      QTemporaryFile *tmp = new QTemporaryFile(QStringLiteral("%1/okrXXXXXX").arg(QDir::tempPath()),this);
      if(!tmp->open()) qCWarning(OkularEpuDebug) << "EPUB : error creating temporary video file";
      if(tmp->write(data,size) == -1) qCWarning(OkularEpuDebug) << "EPUB : error writing data" << tmp->errorString();
      tmp->flush();
      resource.setValue(tmp->fileName());
      break;
    }
    case EpubDocument::AudioResource: {
      QByteArray ba(data,size);
      resource.setValue(ba);
      break;
    }
    default:
      resource.setValue(QString::fromUtf8(data));
      break;
    }

    free(data);
  }

  // add to cache
  addResource(type, name, resource); 

  return resource;
}
开发者ID:KDE,项目名称:okular,代码行数:57,代码来源:epubdocument.cpp


注:本文中的QTemporaryFile::errorString方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。