static bool copyIfNotPresent ( const QString &sourcePath , const QString &destinationPath ) { QFile sourceFile(sourcePath); QFile destinationFile(destinationPath); if (destinationFile.exists()) return true; if (sourceFile.open(QIODevice::ReadOnly | QIODevice::Text) == false) { fprintf(stderr, "Failed to read template.\n"); return false; } QFileInfo destinationInfo(destinationFile); QDir(destinationInfo.absolutePath()).mkpath("."); if (destinationFile.open(QIODevice::WriteOnly | QIODevice::Text) == false) { fprintf(stderr, "Failed to open user configuration file for writing.\n"); return false; } QTextStream in(&sourceFile); QTextStream out(&destinationFile); out << in.readAll(); return true; }
void createFile(const QString pTemplate, const QString pDestination, const QString pClassName ) { // Open template file to read. QFile templateFile( pTemplate ); if ( !templateFile.open(QFile::ReadOnly | QFile::Text) ) { fprintf(stderr, "The project cannot be created because the template file '%s' could not be found.\n", pTemplate.toAscii().data()); exit(1); /* exit status of the program : non-zero for errors */ } // Open project file to write QFile destinationFile( pDestination ); if ( !destinationFile.open(QFile::WriteOnly | QFile::Text) ) { fprintf(stderr, "The project cannot be created because the file '%s' could not be opened.\n", pDestination.toAscii().data()); exit(1); /* exit status of the program : non-zero for errors */ } // Copy from template file to project file // Replace magic words QTextStream out( &destinationFile ); QTextStream in( &templateFile ); QString line; do { line = in.readLine(); line.replace( "<%=class_name%>", pClassName ); out << line << "\n";; } while (!line.isNull()); destinationFile.close(); templateFile.close(); }
bool KNMusicGlobal::renameMusicFile(const QString &originalPath, const QString &preferName) { QFileInfo originalFile(originalPath); //If the original file is not if(!originalFile.exists()) { //Tell the user that original file cannot find. KNMessageBox::information("Error", tr("Cannot find file:\n") + originalFile.absoluteFilePath()); return false; } //Check the prefer name's availability. QFileInfo destinationFile(originalFile.absolutePath()+"/"+preferName); if(destinationFile.exists()) { if(!KNMessageBox::question("Overwrite", tr("File %1 has been exist in folder:\n%2\nOverwrite?").arg( destinationFile.fileName(), destinationFile.absolutePath()))) { return false; } } bool restoreNowPlaying=false; //Check is the file playing. if(m_nowPlaying->currentAnalaysisItem().detailInfo.filePath ==originalFile.absoluteFilePath()) { //Backup the current playing. m_nowPlaying->backupCurrentPlaying(); //Set the flag. restoreNowPlaying=true; } //Rename the music file. bool renameResult=KNGlobal::renameFile(originalFile.absoluteFilePath(), destinationFile.absoluteFilePath()); if(renameResult) { //Emit the file name changed signal. emit musicFilePathChanged(originalFile.absoluteFilePath(), destinationFile.absoluteFilePath(), destinationFile.fileName()); } //Restore the now playing according to the flag. if(restoreNowPlaying) { m_nowPlaying->restoreCurrentPlaying(); } return renameResult; }
QString SyncProcess::updateEntry(const QString & path, const QDir & source, const QDir & destination) { QFileInfo sourceInfo(path); QString relativePath = source.relativeFilePath(path); QString destinationPath = destination.absoluteFilePath(relativePath); QFileInfo destinationInfo(destinationPath); if (sourceInfo.isDir()) { if (!destinationInfo.exists()) { progress->addText(tr("Create directory %1\n").arg(destinationPath)); if (!destination.mkdir(relativePath)) { return QObject::tr("Create '%1' failed").arg(destinationPath); } } } else { if (!destinationInfo.exists()) { // qDebug() << "Copy" << path << "to" << destinationPath; progress->addText(tr("Copy %1 to %2").arg(path).arg(destinationPath) + "\n"); if (!QFile::copy(path, destinationPath)) { return QObject::tr("Copy '%1' to '%2' failed").arg(path).arg(destinationPath); } } else if (sourceInfo.lastModified() > destinationInfo.lastModified()) { // retrieve source contents QFile sourceFile(path); if (!sourceFile.open(QFile::ReadOnly)) { return QObject::tr("Open '%1' failed").arg(path); } QByteArray sourceContents = sourceFile.readAll(); sourceFile.close(); // retrieve destination contents QFile destinationFile(destinationPath); if (!destinationFile.open(QFile::ReadOnly)) { return QObject::tr("Open '%1' failed").arg(destinationPath); } QByteArray destinationContents = destinationFile.readAll(); destinationFile.close(); if (contentsDifferent(sourceContents, destinationContents)) { // copy contents if (!destinationFile.open(QFile::WriteOnly | QIODevice::Truncate)) { return QObject::tr("Write '%1' failed").arg(destinationPath); } progress->addText(tr("Write %1").arg(destinationPath) + "\n"); // qDebug() << "Write" << destinationPath; destinationFile.write(sourceContents); destinationFile.close(); } } } return QString(); }
void File::Rename(const String &source, const String &destination) { if(!Exist(source)) throw Exception(String("Rename: source file does not exist: ") + source); if(Exist(destination)) Remove(destination); if(std::rename(source.pathEncode().c_str(), destination.pathEncode().c_str()) == 0) return; // std::rename will fail to copy between filesystems, so we need to try manually File sourceFile(source, Read); File destinationFile(destination, Truncate); sourceFile.read(destinationFile); sourceFile.close(); destinationFile.close(); Remove(source); }
void FileCopyJob::copyFile() { // Open the source file for reading QFile sourceFile(m_source); if (!sourceFile.open(QFile::ReadOnly)) { setError(CopySourceError); setErrorText(sourceFile.errorString()); emitResult(); return; } // Open destination file for writing QFile destinationFile(m_destination); if (!destinationFile.open(QFile::WriteOnly)) { setError(CopyDestinationError); setErrorText(destinationFile.errorString()); emitResult(); return; } qint64 total = sourceFile.size(); qint64 bytesCopied = 0; while (!sourceFile.atEnd()) { // Read 8KB from the source file at once QByteArray data = sourceFile.read(8192); bytesCopied += data.size(); // Write to the destination destinationFile.write(data); // Emit the percentage emitPercent(bytesCopied, total); } if (m_isMove) { // Remove the source file if (!sourceFile.remove()) { // The source file could not be removed hence we remove the destination // file and trigger an error destinationFile.remove(); setError(MoveSourceError); setErrorText(sourceFile.errorString()); return; } } }
void FlashcardsDeck::saveResources (QString deckFileName, bool verbose) { if (resourceAbsoluteToDeckPathMap.empty()) return; verify (!(mediaDirectoryName.isEmpty() || mediaDirectoryName.isNull()), "Media directory not specified or empty."); QDir createMediaIn = QFileInfo (deckFileName).dir(); verify (createMediaIn.exists(), "Failed to access parent directory of '" + deckFileName + "'."); verify (createMediaIn.mkpath (mediaDirectoryName), "Failed to create media subdirectory '" + mediaDirectoryName + "' for deck file '" + deckFileName +"'."); for (std::pair <QString, QString> absoluteToRelative : resourceAbsoluteToDeckPathMap.toStdMap()) { QString destination = createMediaIn.absolutePath() + "/" + mediaDirectoryName + "/" + absoluteToRelative.second; QFileInfo sourceFile (absoluteToRelative.first), destinationFile (destination); if (destinationFile.exists() && sourceFile.lastModified() == destinationFile.lastModified() && sourceFile.size() == destinationFile.size()) { if (verbose) qstderr << "File '" << absoluteToRelative.first << "' has same last accessed time as '" << destination << "': skipping." << endl; continue; } //bool copied = QFile::copy (absoluteToRelative.first, destination); // Copy preserving timestamps via 'cp' bool copied = false; #ifdef Q_OS_LINUX QProcess process; process.start ("cp", QStringList() << sourceFile.absoluteFilePath() << destinationFile.absoluteFilePath() << "--preserve=timestamps"); verify (process.waitForFinished(), "Failed to wait for 'cp' to finish."); copied = process.exitCode() == 0; #else #error This platform is not supported. Add more cases or test if the existing code works. #endif verify (copied, "Failed to copy '" + absoluteToRelative.first + "' to '" + destination + "'."); if (verbose) qstderr << "Copied resource '" + absoluteToRelative.first + "' to '" + destination + "'." << endl; } if (verbose) qstderr << resourceAbsoluteToDeckPathMap.size() << " resources saved." << endl; }
void merge(int argc, char** argv) { //Syntax: join [destination_file] [parts...] if (argc >= 2) { QString destinationFile(argv[0]); argc--; ++*argv; QList<QString> parts; int index = 0; while (index != argc) { parts << QString(argv[index]); index++; } PartProcessor *core = new PartProcessor(parts, destinationFile, QModelIndex(), PartProcessor::kMerge); core->deleteLater(); //TODO: connect signals and implement them to show progress in terminal core->start(); core->wait(); } else { help(PartProcessor::kMerge); } }
bool convertEEprom(const QString &sourceEEprom, const QString &destinationEEprom, const QString &firmwareFilename) { Firmware *currentFirmware = GetCurrentFirmware(); FirmwareInterface firmware(firmwareFilename); if (!firmware.isValid()) return false; unsigned int version = firmware.getEEpromVersion(); unsigned int variant = firmware.getEEpromVariant(); QFile sourceFile(sourceEEprom); int eeprom_size = sourceFile.size(); if (!eeprom_size) return false; if (!sourceFile.open(QIODevice::ReadOnly)) return false; QByteArray eeprom(eeprom_size, 0); long result = sourceFile.read(eeprom.data(), eeprom_size); sourceFile.close(); QSharedPointer<RadioData> radioData = QSharedPointer<RadioData>(new RadioData()); if (!loadEEprom(*radioData, (uint8_t *)eeprom.data(), eeprom_size) || !currentFirmware->saveEEPROM((uint8_t *)eeprom.data(), *radioData, variant, version)) return false; QFile destinationFile(destinationEEprom); if (!destinationFile.open(QIODevice::WriteOnly)) return false; result = destinationFile.write(eeprom.constData(), eeprom_size); destinationFile.close(); if (result != eeprom_size) return false; return true; }
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); canUpdate=false; QSettings settings; QString dir=QFileDialog::getExistingDirectory(NULL,"Folder containing region directory",settings.value("mapfolder").toString()); if(dir.isEmpty()) abort(); if(!QString(TMPDATA).endsWith("/")) abort(); if(!dir.endsWith("/")) dir+="/"; settings.setValue("mapfolder",dir); QDir().mkpath(TMPDATA); QDir dir2("/tmp/map-metadata/"); dir2.setFilter(QDir::Files | QDir::Dirs | QDir::Hidden | QDir::NoSymLinks | QDir::NoDotAndDotDot); QFileInfoList list = dir2.entryInfoList(); if(!QDir("/tmp/map-metadata/").exists() || list.size()==0) { process.setArguments(QStringList() << "/home/user/Desktop/CatchChallenger/datapack-pkmn/map/main/gen4/map/"); process.setProgram("/home/user/Desktop/CatchChallenger/tools/build-map2png-Desktop-Debug/map2png"); process.setWorkingDirectory("/tmp/map-metadata/"); process.start(); process.waitForFinished(999999999); std::cerr << process.errorString().toStdString() << std::endl; std::cout << process.readAll().toStdString() << std::endl; if(process.exitCode()!=0) std::cerr << "Process exit code: " << process.exitCode() << std::endl; } QString path=QCoreApplication::applicationDirPath()+"/changes.db"; QFile destinationFile(path); if(!destinationFile.exists()) { if(QFile::copy(":/changes.db",path)) { if(!destinationFile.setPermissions(destinationFile.permissions() | QFileDevice::WriteOwner | QFileDevice::WriteUser)) std::cerr << "Unable to set db permissions" << std::endl; } else std::cerr << "Unable to copy the :/changes.db" << std::endl; } m_db = QSqlDatabase::addDatabase("QSQLITE"); m_db.setDatabaseName(path); if (!m_db.open()) { qDebug() << "Error: connection with database fail"; abort(); } QHash<QString,MapContent> db_finishedFile; QHash<QString,MapContent> db_not_finishedFile; QSqlQuery query; if(!query.exec("SELECT file, region, zone, subzone, name, type, finished FROM maps")) { qDebug() << query.lastError().text(); abort(); } while(query.next()) { QString file = query.value(0).toString(); MapContent mapContent; mapContent.region=query.value(1).toString(); mapContent.zone=query.value(2).toString(); mapContent.subzone=query.value(3).toString(); mapContent.name=query.value(4).toString(); mapContent.type=query.value(5).toString(); if(mapContent.region.isEmpty()) abort(); mapContent.officialzone=query.value(7).toInt()>0; if(query.value(6).toInt()>0) db_finishedFile[file]=mapContent; else db_not_finishedFile[file]=mapContent; } { QDirIterator it(dir,QDirIterator::Subdirectories); QRegularExpression regex("\\.tmx$"); QRegularExpression regexRemove("^/"); while (it.hasNext()) { QString element=it.next(); if(element.contains(regex)) { QString sortPath=element; sortPath.remove(0,dir.size()); sortPath.remove(regexRemove); QString pngDest=TMPDATA+sortPath; pngDest.replace(".tmx",".png"); //std::cout << sortPath.toStdString() << " -> " << pngDest.toStdString() << std::endl; const QStringList elementList=sortPath.split("/"); if(elementList.size()>=2 && elementList.size()<=3) { QString file = sortPath; if(db_finishedFile.contains(file)) finishedFile[file]=db_finishedFile.value(file); else if(db_not_finishedFile.contains(file)) not_finishedFile[file]=db_not_finishedFile.value(file); else { MapContent mapContent; mapContent.region=elementList.at(0); if(mapContent.region.isEmpty()) abort(); mapContent.zone=elementList.at(1); mapContent.zone.replace(".tmx",""); if(elementList.size()==3) { mapContent.subzone=elementList.at(2); mapContent.subzone.replace(".tmx",""); } mapContent.officialzone=true; //get from xml QDomDocument domDocument; QString xmlpath=element; xmlpath.replace(".tmx",".xml"); QFile xmlfile(xmlpath); if (xmlfile.open(QIODevice::ReadOnly)) { if (!domDocument.setContent(&xmlfile)) { xmlfile.close(); return; } xmlfile.close(); const tinyxml2::XMLElement root = domDocument.RootElement(); if(root.tagName()=="map") { //load the content const tinyxml2::XMLElement nameItem = root.FirstChildElement("name"); if(!nameItem.isNull()) mapContent.name=nameItem.text(); if(root.hasAttribute("type")) mapContent.type=root.attribute("type"); if(root.hasAttribute("zone")) { mapContent.officialzone=true; mapContent.zone=root.attribute("zone"); } else { if(mapContent.name.startsWith("Route ")) { mapContent.officialzone=false; mapContent.zone="route"; } else mapContent.officialzone=true; } } } not_finishedFile[file]=mapContent; //insert into database QSqlQuery query; if(!query.prepare("INSERT INTO maps (file, region, zone, subzone, name, type, finished) " "VALUES (:file, :region, :zone, :subzone, :name, :type, :finished)")) { qDebug() << query.lastError().text(); abort(); } query.bindValue(":file", file); query.bindValue(":region", mapContent.region); query.bindValue(":zone", mapContent.zone); query.bindValue(":subzone", mapContent.subzone); query.bindValue(":name", mapContent.name); query.bindValue(":type", mapContent.type); query.bindValue(":finished", 0); if(!query.exec()) { qDebug() << query.lastError().text(); abort(); } } } } } } preload_the_map(dir.toStdString()); for(auto& n:map_list) { CatchChallenger::MapServer * map=n.second; unsigned int index=0; while(index<map->linked_map.size()) { CatchChallenger::CommonMap * const newMap=map->linked_map.at(index); if(!vectorcontainsAtLeastOne(newMap->linked_map,static_cast<CatchChallenger::CommonMap *>(map))) newMap->linked_map.push_back(map); index++; } } displayNewNotFinishedMap(); updateProgressLabel(); }
bool ProjectResourcesCopier::CopyAllResourcesTo(gd::Project & originalProject, AbstractFileSystem & fs, gd::String destinationDirectory, bool updateOriginalProject, wxProgressDialog * optionalProgressDialog, bool askAboutAbsoluteFilenames, bool preserveDirectoryStructure) { //Check if there are some resources with absolute filenames gd::ResourcesAbsolutePathChecker absolutePathChecker(fs); originalProject.ExposeResources(absolutePathChecker); bool copyAlsoResourcesWithAbsolutePath = !askAboutAbsoluteFilenames; std::cout << "Copying all ressources to " << destinationDirectory; #if !defined(GD_NO_WX_GUI) if ( !copyAlsoResourcesWithAbsolutePath ) { copyAlsoResourcesWithAbsolutePath = absolutePathChecker.HasResourceWithAbsoluteFilenames() && wxMessageBox(_("Some resources are using absolute filenames.\nDo you want them to be copied in the new folder of the project? If you choose No, they won't be modified."), _("Some resources are using absolute filenames."), wxYES_NO | wxICON_QUESTION) == wxYES; } #endif //Get the resources to be copied gd::ResourcesMergingHelper resourcesMergingHelper(fs); resourcesMergingHelper.SetBaseDirectory(fs.DirNameFrom(originalProject.GetProjectFile())); resourcesMergingHelper.PreserveDirectoriesStructure(preserveDirectoryStructure); resourcesMergingHelper.PreserveAbsoluteFilenames(!copyAlsoResourcesWithAbsolutePath); if ( updateOriginalProject ) { originalProject.ExposeResources(resourcesMergingHelper); } else { std::shared_ptr<gd::Project> project(new gd::Project(originalProject)); project->ExposeResources(resourcesMergingHelper); } //Copy resources map<gd::String, gd::String> & resourcesNewFilename = resourcesMergingHelper.GetAllResourcesOldAndNewFilename(); unsigned int i = 0; for(map<gd::String, gd::String>::const_iterator it = resourcesNewFilename.begin(); it != resourcesNewFilename.end(); ++it) { if ( !it->first.empty() ) { #if !defined(GD_NO_WX_GUI) if ( optionalProgressDialog ) { if ( !optionalProgressDialog->Update(i/static_cast<float>(resourcesNewFilename.size())*100.0f, _("Exporting ")+it->second) ) return false; //User choose to abort. } #endif //Create the destination filename gd::String destinationFile(destinationDirectory + "/" + it->second); fs.MakeAbsolute(destinationFile, destinationDirectory); if ( destinationFile != it->first ) { //Be sure the directory exists gd::String dir = fs.DirNameFrom(destinationFile); if ( !fs.DirExists(dir) ) fs.MkDir(dir); //We can now copy the file if ( !fs.CopyFile(it->first, destinationFile) ) { gd::LogWarning( _( "Unable to copy \"")+it->first+_("\" to \"")+destinationFile+_("\".")); } } } ++i; } return true; }
void ReadWidget::exportFile() { if(reader == 0) { QMessageBox messageBox; messageBox.setText(QString(tr("You must load a resource file."))); messageBox.exec(); return; } QList<int> rows = tableView->getSelectedRows(); if(rows.size() == 0) { QMessageBox messageBox; messageBox.setText(QString(tr("You must select at least one file to export."))); messageBox.exec(); return; } QStringList names; for(int i = 0; i < rows.size(); i++) { names << tableModel->data(tableModel->index(rows[i], 1)).toString(); } QString directoryPath = QFileDialog::getExistingDirectory(this, tr("Select a destination directory."), ".", 0); if(directoryPath.size() == 0) // the user hit cancel { return; } if(!directoryPath.endsWith('/') && !directoryPath.endsWith('\\')) { directoryPath.append('/'); } for(int i = 0; i < names.size(); i++) { string name = names[i].toStdString(); QString path = directoryPath + names[i]; QFile destinationFile(path); if(destinationFile.exists()) { QMessageBox replaceConfirm; replaceConfirm.setText("A file \""+destinationFile.fileName()+"\" already exists."); replaceConfirm.setInformativeText("Do you want to replace this file?"); replaceConfirm.setStandardButtons(QMessageBox::Yes | QMessageBox::No); replaceConfirm.setDefaultButton(QMessageBox::Yes); if(replaceConfirm.exec() == QMessageBox::No) { continue; } } char * fileDataRaw = reader->getFile(name); destinationFile.open(QIODevice::WriteOnly); QDataStream output(&destinationFile); output.writeRawData(fileDataRaw, reader->getEntryFileSize(name)); destinationFile.close(); delete fileDataRaw; } }
KLUPD::CoreError KLUPD::AdministrationKitProtocol::getFile( const Path &fileName, const Path &localPath, const Path &relativeUrlPathIn, const bool useMasterAdministrationServer) { #ifdef DISABLE_AK_FILETRANSFER TRACE_MESSAGE("Administration Kit Transport is not implemented"); return CORE_DOWNLOAD_ERROR; #else // skip initial slash in relative URL path Path relativeUrlPath = relativeUrlPathIn; if(!relativeUrlPath.empty() && (relativeUrlPath[0] == L'\\' || relativeUrlPath[0] == L'/')) { relativeUrlPath = relativeUrlPath.toWideChar() + 1; } const Path path = relativeUrlPath + fileName; /////////////////////////////////////////////// /// checking current state and parameters const CoreError connectionResult = setupLowLevelConnectionIfNeed(useMasterAdministrationServer); if(connectionResult != CORE_NO_ERROR) { TRACE_MESSAGE2("Failed to setup connection to Administration Server, result '%S'", toString(connectionResult).toWideChar()); return connectionResult; } /////////////////////////////////////////////// /// receiving data by portions size_t regettingPosition = LocalFile(localPath + fileName).size(); AutoStream destinationFile(pLog); while(true) { // check if request should be cancelled if(m_downloadProgress.checkCancel()) { TRACE_MESSAGE2("File transfer cancelled '%S'", path.toWideChar()); return CORE_CANCELLED; } const long localBufferSize = 65536; std::vector<unsigned char> localBuffer(localBufferSize, 0); int bytesRead = 0; m_downloadProgress.updateSpeedStartTimer(); const KLFT::FileOpeartionResult getChunkResult = m_adminKitTransprot->GetFileChunk( path.toWideChar(), regettingPosition, &localBuffer[0], localBuffer.size(), bytesRead); m_downloadProgress.updateSpeedStopTimer(); // a portion of file got successfully if(getChunkResult == KLFT::FR_Ok || getChunkResult == KLFT::FR_OkDownloaded) { const CoreError saveDataToFileResult = saveDataToFile( localPath + fileName, &localBuffer[0], bytesRead, regettingPosition != 0, destinationFile, pLog); if(!isSuccess(saveDataToFileResult)) { TRACE_MESSAGE3("Failed to write data obtained from Administration Server to file '%S', result '%S'", path.toWideChar(), toString(saveDataToFileResult).toWideChar()); return saveDataToFileResult; } regettingPosition += bytesRead; m_downloadProgress.bytesTransferred(bytesRead); // file has been completely downloaded if(getChunkResult == KLFT::FR_OkDownloaded) return CORE_NO_ERROR; continue; } TRACE_MESSAGE5("Failed to obtain file chunk from Administration Server, file '%S', result '%s', bytes read %d, current position %d", path.toWideChar(), toString(getChunkResult).c_str(), bytesRead, regettingPosition); if(getChunkResult == KLFT::FR_Timeout) { // TODO check if time out is over and error should be returned continue; } // error while download happened switch(getChunkResult) { // invalid AdminKit Transport identifier: either receiver was deleted or connect was already called for this receiver case KLFT::FR_WrongReceiverId: return CORE_AK_WrongReceiverId; // invalid arguments for AdminKit Transport // wrong offset is requested, consider file is downloaded and signature should be checked case KLFT::FR_WrongArguments: { // TODO: this is *work around* about the problem that AdminKit returns return CORE_NO_ERROR; // FR_WrongArguments code in case source contains // valid file in target download folder // this code can be deleted when problem is fixed in AdminKit } // file not found on AdminKit server case KLFT::FR_FileNotFound: return CORE_NO_SOURCE_FILE; // AdminKit transport file receive error case KLFT::FR_ErrorInOperation: return CORE_AK_ErrorInOperation; // unknown AdminKit transport receive operation error default: return CORE_AK_UnknownError; } } #endif // DISABLE_AK_FILETRANSFER }