bool importPublicKey( ItalcCore::UserRole role, const QString &pubKey, const QString &destDir ) { // look whether the public key file is valid PublicDSAKey dsaKey( pubKey ); if( !dsaKey.isValid() ) { qCritical() << "ImcCore::importPublicKey(): file" << pubKey << "is not a valid public key file"; return false; } QString pub = LocalSystem::Path::publicKeyPath( role, destDir ); QFile destFile( pub ); if( destFile.exists() ) { destFile.setPermissions( QFile::WriteOwner ); if( !destFile.remove() ) { qCritical() << "ImcCore::importPublicKey(): could not remove " "existing public key file" << destFile.fileName(); return false; } } // now try to copy it return dsaKey.save( pub ); }
bool UpdateClient::copyFile(const QString &srcDir, const QString &destDir, const QString &srcFileName, const QString &destFileName) { QFileInfo sourceFile(QDir::cleanPath(srcDir + QDir::separator() + srcFileName)); QFileInfo destFile(QDir::cleanPath(destDir + QDir::separator() + destFileName)); //if source file doesn't exists if (!QFile::exists(sourceFile.filePath())) { return false; } // check if dest directory not exists if (!QDir(QDir::cleanPath(destFile.absolutePath())).exists()) { // try to create dest dir if (!QDir(QDir::rootPath()).mkpath(destFile.absolutePath())) return false; } // if dest file exists if (QFile::exists(destFile.filePath())) { // remove it (analog rewrite functionality) QFile::remove(destFile.filePath()); } return QFile::copy(sourceFile.filePath(), destFile.filePath()); }
bool ZipArchive::extract(boost::filesystem::path from, boost::filesystem::path where, std::vector<std::string> what) { unzFile archive = unzOpen2_64(from.c_str(), FileStream::GetMinizipFilefunc()); auto onExit = vstd::makeScopeGuard([&]() { unzClose(archive); }); for (const std::string & file : what) { if (unzLocateFile(archive, file.c_str(), 1) != UNZ_OK) return false; const boost::filesystem::path fullName = where / file; const boost::filesystem::path fullPath = fullName.parent_path(); boost::filesystem::create_directories(fullPath); // directory. No file to extract // TODO: better way to detect directory? Probably check return value of unzOpenCurrentFile? if (boost::algorithm::ends_with(file, "/")) continue; FileStream destFile(fullName, std::ios::out | std::ios::binary); if (!destFile.good()) return false; if (!extractCurrent(archive, destFile)) return false; } return true; }
void ExtractZipArchive(wxInputStream &stream, const wxString &dest) { wxZipInputStream zipStream(stream); std::auto_ptr<wxZipEntry> entry; while (entry.reset(zipStream.GetNextEntry()), entry.get() != NULL) { if (entry->IsDir()) continue; wxString name = entry->GetName(); wxFileName destFile(dest + (name.StartsWith(_("/")) ? _("") : _("/")) + name); destFile.Mkdir(0777, wxPATH_MKDIR_FULL); if (destFile.FileExists()) wxRemoveFile(destFile.GetFullPath()); wxFFileOutputStream outStream(destFile.GetFullPath()); outStream.Write(zipStream); // wxFFile file(destFile.GetFullPath(), _("w")); // // const size_t bufSize = 1024; // void *buffer = new char[bufSize]; // while (!zipStream.Eof()) // { // zipStream.Read(buffer, bufSize); // file.Write(buffer, bufSize); // } // file.Flush(); } }
bool QgsGplColorScheme::setColors( const QgsNamedColorList &colors, const QString &context, const QColor &baseColor ) { Q_UNUSED( context ); Q_UNUSED( baseColor ); QString destFilePath = gplFilePath(); if ( destFilePath.isEmpty() ) { return false; } QFile destFile( destFilePath ); if ( QgsSymbolLayerUtils::saveColorsToGpl( destFile, schemeName(), colors ) ) { if ( QgsApplication::colorSchemeRegistry()->randomStyleColorScheme() == this ) { // force a re-generation of the random style color list, since the color list has changed QgsApplication::colorSchemeRegistry()->setRandomStyleColorScheme( this ); } return true; } else { return false; } }
status_t copy_data(const entry_ref& source, const entry_ref& dest) { status_t err; unsigned char* buffer; buffer = new unsigned char[BUFFERLEN]; ssize_t nRead; BFile srcFile(&source, O_RDONLY); if ((err = srcFile.InitCheck()) != B_NO_ERROR) return err; BFile destFile(&dest, O_WRONLY | O_CREAT | O_TRUNC); if ((err = destFile.InitCheck()) != B_NO_ERROR) return err; struct stat info; if ((err = srcFile.GetStat(&info)) != B_NO_ERROR) return err; if ((err = destFile.SetSize(info.st_size)) != B_NO_ERROR) return err; if ((err = destFile.Seek(0, SEEK_SET)) != B_NO_ERROR) return err; while ((nRead = srcFile.Read(buffer, BUFFERLEN)) > 0) { err = destFile.Write(buffer, nRead); if (err < 0) return err; } delete buffer; return B_OK; }
bool ZipArchive::extract(std::string from, std::string where, std::vector<std::string> what) { unzFile archive = unzOpen(from.c_str()); auto onExit = vstd::makeScopeGuard([&]() { unzClose(archive); }); for (std::string & file : what) { if (unzLocateFile(archive, file.c_str(), 1) != UNZ_OK) return false; std::string fullName = where + '/' + file; std::string fullPath = fullName.substr(0, fullName.find_last_of("/")); boost::filesystem::create_directories(fullPath); // directory. No file to extract // TODO: better way to detect directory? Probably check return value of unzOpenCurrentFile? if (boost::algorithm::ends_with(file, "/")) continue; std::ofstream destFile(fullName, std::ofstream::binary); if (!destFile.good()) return false; if (!extractCurrent(archive, destFile)) return false; } return true; }
int main(int argc, char *argv[]) { if( argc == 2 && strcmp(argv[1], "--help") == 0 ) { QCoreApplication a(argc, argv); // this doesn't work printf("Command line usage:\n\nReplacementWorkspace my-replacements.xml input.txt output.txt\n"); return a.exec(); } else if( argc == 4 ) { // this does nothing and it hangs QCoreApplication a(argc, argv); QString transformationFile( argv[1] ); QString sourceFile( argv[2] ); QString destFile( argv[3] ); ReplacementEngine re; re.readFromFile(transformationFile); re.processFile(sourceFile, destFile); return a.exec(); } else { QApplication a(argc, argv); MainWindow w; w.show(); return a.exec(); } }
bool CWizZiwReader::encryptDataToTempFile(const QString& sourceFileName, \ const QString& destFileName, \ const QString& strZiwCipher) { QFile sourceFile(sourceFileName); if (!sourceFile.open(QIODevice::ReadOnly)) { TOLOG("Can't open source file while encrypt to temp file"); return false; } // encrypt data QByteArray inBytes(sourceFile.readAll()); QByteArray outBytes; if (!WizAESEncryptToString((const unsigned char *)(strZiwCipher.toUtf8().constData()), inBytes, outBytes)) { return false; } // encrypt ziw cipher QByteArray encryptedZiwCipher; if (!encryptZiwCipher(strZiwCipher.toUtf8(), encryptedZiwCipher)) { return false; } // compose file // FIXME: hard coded here. WIZZIWHEADER header; memset(&header, 0, sizeof(header)); header.szSign[0] = 'Z'; header.szSign[1] = 'I'; header.szSign[2] = 'W'; header.szSign[3] = 'R'; header.nVersion = 1; header.nKeyLength = WIZZIWFILE_KEY_LENGTH; memcpy(header.szEncryptedKey, encryptedZiwCipher.constData(), sizeof(header.szEncryptedKey)); QFile destFile(destFileName); if (!destFile.open(QIODevice::WriteOnly | QIODevice::Truncate)) { TOLOG("Can't open dest file while encrypt to temp file"); return false; } QDataStream out(&destFile); if (sizeof(header) != out.writeRawData((const char *)&header, sizeof(header))) { TOLOG("Write data failed while encrypt to temp file"); destFile.remove(); return false; } if (outBytes.length() != out.writeRawData(outBytes.constData(), outBytes.length())) { TOLOG("Write data failed while encrypt to temp file"); destFile.remove(); return false; } destFile.close(); sourceFile.close(); return true; }
void UBWidgetUniboardAPI::onDownloadFinished(bool pSuccess, sDownloadFileDesc desc, QByteArray pData) { //if widget recieves is waiting for this id then process if (!takeIDWidget(desc.id)) return; if (!pSuccess) { qDebug() << "can't download the whole data. An error occured"; return; } QString contentType = desc.contentTypeHeader; QString extention = UBFileSystemUtils::fileExtensionFromMimeType(contentType); if (!supportedTypeHeader(contentType)) { qDebug() << "actions for mime type" << contentType << "are not supported"; return; } QString objDir = getObjDir(); if (!QDir().exists(objDir)) { if (!QDir().mkpath(objDir)) { qDebug() << "can't create objects directory path. Check the permissions"; return; } } QString destFileName = objDir + QUuid::createUuid() + "." + extention; QFile destFile(destFileName); if (!destFile.open(QIODevice::WriteOnly)) { qDebug() << "can't open" << destFileName << "for wrighting"; return; } if (destFile.write(pData) == -1) { qDebug() << "can't implement data writing"; return; } QGraphicsView *tmpView = mGraphicsWidget->scene()->views().at(0); QPoint dropPoint(mGraphicsWidget->mapFromScene(tmpView->mapToScene(desc.dropPoint)).toPoint()); QMimeData dropMimeData; QString mimeText = createMimeText(true, contentType, destFileName); dropMimeData.setData(tMimeText, mimeText.toAscii()); destFile.close(); //To make js interpreter accept drop event we need to generate move event first. QDragMoveEvent pseudoMove(dropPoint, desc.dropActions, &dropMimeData, desc.dropMouseButtons, desc.dropModifiers); QApplication::sendEvent(mGraphicsWidget,&pseudoMove); QDropEvent readyEvent(dropPoint, desc.dropActions, &dropMimeData, desc.dropMouseButtons, desc.dropModifiers); //sending event to destination either it had been downloaded or not QApplication::sendEvent(mGraphicsWidget,&readyEvent); readyEvent.acceptProposedAction(); }
bool aService::copyFile(const QString& srcFileName, const QString& destFileName, bool replaceIfExists) { QFile srcFile(srcFileName); QFile destFile(destFileName); if(!srcFile.exists()) { aLog::print(aLog::MT_ERROR, QObject::tr("aService copy: source file %1 not exist").arg(srcFileName)); return false; } if(destFile.exists() && !replaceIfExists) { aLog::print(aLog::MT_ERROR, QObject::tr("aService copy: replace destination file %1").arg(destFileName)); return false; } if(!srcFile.open( IO_ReadOnly )) { aLog::print(aLog::MT_ERROR, QObject::tr("aService copy: source file %1 open for read error").arg(srcFileName)); return false; } if(!destFile.open( IO_WriteOnly)) { aLog::print(aLog::MT_ERROR, QObject::tr("aService copy: destination file %1 open for write error").arg(destFileName)); return false; } const int BUFFER_SIZE = 1024; Q_INT8 buffer[BUFFER_SIZE]; QDataStream srcStream(&srcFile); QDataStream destStream(&destFile); while(!srcStream.atEnd()) { int i = 0; while(!srcStream.atEnd() && i < BUFFER_SIZE) { srcStream >> buffer[i]; i++; } for(int k = 0; k < i; k++) { destStream << buffer[k]; } } srcFile.close(); destFile.close(); aLog::print(aLog::MT_INFO, QObject::tr("aService copy file %1 to %2 ok").arg(srcFileName).arg(destFileName)); return true; }
bool fileCopy(const string& src, const string& dest) { ifstream srcFile(src,ios_base::binary); ofstream destFile(dest, ios_base::binary); char buffer[1024]; while(!srcFile.eof()){ srcFile.read(buffer, 1024); destFile.write(buffer,1024); } return true; }
bool ResourceOps::CopyFile(File* srcFile, const String& destFileName) { SharedPtr<File> destFile(new File(context_, destFileName, FILE_WRITE)); if (!destFile->IsOpen()) return false; unsigned fileSize = srcFile->GetSize(); SharedArrayPtr<unsigned char> buffer(new unsigned char[fileSize]); unsigned bytesRead = srcFile->Read(buffer.Get(), fileSize); unsigned bytesWritten = destFile->Write(buffer.Get(), fileSize); return bytesRead == fileSize && bytesWritten == fileSize; }
void saveConfig(const Json::Value &options) { std::string saveConfigFilename = options["save"].get("config","").asString(); if (saveConfigFilename == "") return; std::ofstream destFile(saveConfigFilename.c_str()); if (! destFile.good()) { std::cerr << "WARNING: not saving config file due to problem opening destination file: " << saveConfigFilename << std::endl; return; } Json::StyledStreamWriter writer(" "); writer.write(destFile,options); destFile.close(); }
void File::copyTo(const std::string& path) const { Path src(getPathImpl()); Path dest(path); File destFile(path); if ((destFile.exists() && destFile.isDirectory()) || dest.isDirectory()) { dest.makeDirectory(); dest.setFileName(src.getFileName()); } if (isDirectory()) copyDirectory(dest.toString()); else copyToImpl(dest.toString()); }
void t4p::ExplorerModifyActionClass::BackgroundWork() { wxFileName parentDir; wxString name; bool totalSuccess = true; std::vector<wxFileName> dirsDeleted; std::vector<wxFileName> dirsNotDeleted; std::vector<wxFileName> filesDeleted; std::vector<wxFileName> filesNotDeleted; if (t4p::ExplorerModifyActionClass::DELETE_FILES_DIRS == Action) { std::vector<wxFileName>::iterator d; for (d = Dirs.begin(); d != Dirs.end(); ++d) { bool success = t4p::RecursiveRmDir(d->GetPath()); if (success) { wxFileName wxFileName; wxFileName.AssignDir(d->GetPath()); dirsDeleted.push_back(wxFileName); } else { wxFileName wxFileName; wxFileName.AssignDir(d->GetPath()); dirsNotDeleted.push_back(wxFileName); } totalSuccess &= success; } std::vector<wxFileName>::iterator f; for (f = Files.begin(); f != Files.end(); ++f) { bool success = wxRemoveFile(f->GetFullPath()); if (success) { wxFileName deletedFile(f->GetFullPath()); filesDeleted.push_back(deletedFile); } else { wxFileName deletedFile(f->GetFullPath()); filesNotDeleted.push_back(deletedFile); } totalSuccess &= success; } t4p::ExplorerModifyEventClass modEvent(GetEventId(), dirsDeleted, filesDeleted, dirsNotDeleted, filesNotDeleted, totalSuccess); PostEvent(modEvent); } else if (t4p::ExplorerModifyActionClass::RENAME_FILE == Action) { wxFileName destFile(OldFile.GetPath(), NewName); bool success = wxRenameFile(OldFile.GetFullPath(), destFile.GetFullPath(), false); t4p::ExplorerModifyEventClass modEvent(GetEventId(), OldFile, NewName, success); PostEvent(modEvent); } }
// Function that copies content of source to destination // Destination file will be overwritten // Supports only small files bool Helper::copyFile(const QString& source, const QString& destination) { QFile srcFile(source); if(!srcFile.open(QIODevice::ReadOnly)) return false; QByteArray data = srcFile.readAll(); srcFile.close(); QFile destFile(destination); if(!destFile.open(QIODevice::WriteOnly)) return false; destFile.write(data); destFile.close(); return true; }
void DocumentsDir::generateTemplateDir() { QFileInfoList fil( QDir(":/templates/").entryInfoList() ); QDir templatesDir( getTemplatesDirName() ); if( !templatesDir.mkpath( "." ) ) { return; } foreach( const QFileInfo &fi, fil ) { QString srcFile( fi.absoluteFilePath() ); QString destFile( templatesDir.absoluteFilePath( fi.fileName() ) ); if( QFile::copy( srcFile, destFile ) ) { QFile::setPermissions( destFile, QFile::permissions( destFile ) | QFile::WriteUser ); } }
bool VProjectItemFile::MoveTo(const XBOX::VURL& inSrcURL,const XBOX::VURL& inDestURL) { bool ok = false; VFilePath srcFilePath; inSrcURL.GetFilePath(srcFilePath); VFile srcFile(srcFilePath); if (srcFile.Exists()) { VFilePath destFilePath; inDestURL.GetFilePath(destFilePath); VFile destFile(destFilePath); if (!destFile.Exists()) { if (srcFile.Move(destFilePath, NULL) == VE_OK) ok = true; } } return ok; }
bool FileSystemUtil::copyFile(const QString &from, const QString &to, QString *errorMessage) { QFile sourceFile(from); QFile destFile(to); bool success = sourceFile.open(QIODevice::ReadOnly); if(!success){ *errorMessage = sourceFile.errorString(); return false; } success = destFile.open(QIODevice::WriteOnly); if(!success){ sourceFile.close(); *errorMessage = destFile.errorString(); return false; } destFile.write(sourceFile.readAll()); sourceFile.close(); destFile.close(); return true; }
bool RecursiveDirJobHelper::copyWithReplaceKde4(const QString & sourceFileName, const QString & destFileName) { QFile sourceFile(sourceFileName); QFile destFile(destFileName); if ( !sourceFile.open(QIODevice::ReadOnly) ) { qCritical() << "copyWithReplaceKde4:" << "Could not open" << sourceFileName << "for reading"; return false; } if ( !destFile.open(QIODevice::WriteOnly) ) { qCritical() << "copyWithReplaceKde4:" << "Could not open" << destFileName << "for writing"; return false; } while ( !sourceFile.atEnd() ) { QByteArray b = sourceFile.readLine(); if ( b.isEmpty() ) { qCritical() << "copyWithReplaceKde4:" << "Could not read from" << sourceFileName; return false; } if ( destFile.write( b.replace("/.kde4/", "/.kde/") ) == -1 ) { qCritical() << "copyWithReplaceKde4:" << "Could not write to" << destFileName; return false; } } if ( !destFile.flush() ) { qCritical() << "copyWithReplaceKde4:" << "Could not flush" << destFileName; return false; } destFile.close(); sourceFile.close(); return true; }
// Copy, recursively if necessary, the source to the destination bool Foam::cp(const fileName& src, const fileName& dest) { // Make sure source exists. if (!exists(src)) { return false; } fileName destFile(dest); // Check type of source file. if (src.type() == fileName::FILE) { // If dest is a directory, create the destination file name. if (destFile.type() == fileName::DIRECTORY) { destFile = destFile/src.name(); } // Make sure the destination directory exists. if (!isDir(destFile.path()) && !mkDir(destFile.path())) { return false; } // Open and check streams. std::ifstream srcStream(src.c_str()); if (!srcStream) { return false; } std::ofstream destStream(destFile.c_str()); if (!destStream) { return false; } // Copy character data. char ch; while (srcStream.get(ch)) { destStream.put(ch); } // Final check. if (!srcStream.eof() || !destStream) { return false; } } else if (src.type() == fileName::DIRECTORY) { // If dest is a directory, create the destination file name. if (destFile.type() == fileName::DIRECTORY) { destFile = destFile/src.component(src.components().size() -1); } // Make sure the destination directory exists. if (!isDir(destFile) && !mkDir(destFile)) { return false; } // Copy files fileNameList contents = readDir(src, fileName::FILE, false); forAll(contents, i) { if (POSIX::debug) { Info<< "Copying : " << src/contents[i] << " to " << destFile/contents[i] << endl; } // File to file. cp(src/contents[i], destFile/contents[i]); } // Copy sub directories. fileNameList subdirs = readDir(src, fileName::DIRECTORY); forAll(subdirs, i) { if (POSIX::debug) { Info<< "Copying : " << src/subdirs[i] << " to " << destFile << endl; } // Dir to Dir. cp(src/subdirs[i], destFile); } } return true; }
/** reads the configuration file .cuterc*/ void readConfig() { QDir dir = QDir::home(); if( !dir.cd(".cute") ){ dir.cd(".cute"); QFileInfo fi(dir, ".cute"); if(fi.exists()){ if(fi.isDir()) QMessageBox::warning(qApp->mainWidget(), "CUTE", "Cannot cd into .cute"); else QMessageBox::warning(qApp->mainWidget(), "CUTE", "Cannot create directory"); } else{ QMessageBox::information(qApp->mainWidget(), "CUTE", "Creating ~/.cute directory"); if(!dir.mkdir(".cute")) QMessageBox::information(qApp->mainWidget(), "CUTE", "Could not create ~/.cute directory"); else{ dir.cd(".cute"); if(!dir.mkdir("scripts")) QMessageBox::information(qApp->mainWidget(), "CUTE", "Could not create ~/.cute/scripts directory"); if(!dir.mkdir("macros")) QMessageBox::information(qApp->mainWidget(), "CUTE", "Could not create ~/.cute/macros directory"); if(!dir.mkdir("sessions")) QMessageBox::information(qApp->mainWidget(), "CUTE", "Could not create ~/.cute/sessions directory"); } } } // if cute version >= 0.1.6 langs dir is required if( !QDir(QDir::homeDirPath()+QDir::separator()+".cute"+QDir::separator()+"langs").exists() ) { QDir destDir = QDir::home(); destDir.cd(".cute"); destDir.mkdir("langs"); destDir.cd("langs"); QDir srcDir(LANG_DIR); QString data; QStringList dirList = srcDir.entryList(); for( int i = 2; i < dirList.count(); i++) if( QFileInfo(srcDir.absPath()+QDir::separator()+dirList[i]).isFile()) { QFile srcFile(srcDir.absPath()+QDir::separator()+dirList[i]); QFile destFile(destDir.absPath()+QDir::separator()+dirList[i]); if(destFile.exists()) continue; QTextStream destStream(&destFile); QTextStream srcStream(&srcFile); srcFile.open(IO_ReadOnly); destFile.open(IO_WriteOnly); data = srcStream.read(); destStream << data; srcFile.close(); destFile.close(); } } QFile file(QDir::homeDirPath()+"/.cuterc"); if(!file.exists()){ QMessageBox::information(qApp->mainWidget(), "CUTE", "Creating ~/.cuterc"); file.open(IO_ReadOnly); file.close(); return; } //FILE *c_file = fopen("/home/heiko/.cuterc", "r"); //PyRun_SimpleFile(c_file, ".cuterc"); QString const_cmd("execfile(\".cuterc\")\n"); dir = QDir::current(); QDir::setCurrent( QDir::homeDirPath() ); char *cmd = new char[1024]; strcpy(cmd, const_cmd.latin1()); PyRun_SimpleString(cmd); // read language config files QDir langDir = QDir(QDir::homeDirPath()+QDir::separator()+".cute"+QDir::separator()+"langs"); QStringList langEntryList = langDir.entryList(); QString langFile; for( int i = 2; i < langEntryList.count(); i++ ){ QString langFile = langDir.absPath()+QDir::separator()+langEntryList[i]; QFileInfo fi(langDir, langFile); if(fi.isFile()){ langFile = QString("execfile(\"")+langFile+QString("\")\n"); char *cmd = strdup(langFile); PyRun_SimpleString( cmd ); } } QDir::setCurrent( dir.absPath() ); }
void stk500SaveFiles::saveFile(DirectoryEntry fileEntry, QString sourceFilePath, QString destFilePath, double progStart, double progTotal) { /* Ensure that the parent directory exists */ QString destFolderPath = destFilePath; int destFolderIdx = destFolderPath.lastIndexOf('/'); if (destFolderIdx != -1) { destFolderPath.remove(destFolderIdx, destFolderPath.length() - destFolderIdx); } QDir dir = QDir::root(); dir.mkpath(destFolderPath); /* Open the file for writing */ QFile destFile(destFilePath); if (!destFile.open(QIODevice::WriteOnly)) { throw ProtocolException("Failed to open file for writing"); } /* Proceed to read in data */ quint32 cluster = fileEntry.firstCluster(); if (cluster) { char buff[512]; quint32 remaining = fileEntry.fileSize; quint32 done = 0; qint64 startTime = QDateTime::currentMSecsSinceEpoch(); qint64 time = startTime; qint64 timeElapsed = 0; while (remaining > 0) { quint32 block = protocol->sd().getClusterBlock(cluster); for (int i = 0; i < protocol->sd().volume().blocksPerCluster; i++) { protocol->sd().read(block + i, 0, buff, 512); /* If cancelled, stop reading/writing by setting remaining to 0 */ if (isCancelled()) { remaining = 0; } time = QDateTime::currentMSecsSinceEpoch(); timeElapsed = (time - startTime) / 1000; done = (fileEntry.fileSize - remaining); int speed_ps; if (timeElapsed == 0 || done == 0) { speed_ps = 6000; } else { speed_ps = done / timeElapsed; } /* Update progress */ setProgress(progStart + progTotal * ((double) done / (double) fileEntry.fileSize)); /* Update the status info */ QString newStatus; newStatus.append("Reading ").append(sourceFilePath).append(": "); newStatus.append(stk500::getSizeText(remaining)).append(" remaining ("); newStatus.append(stk500::getSizeText(speed_ps)).append("/s)\n"); newStatus.append("Elapsed: ").append(stk500::getTimeText(timeElapsed)); newStatus.append(", estimated ").append(stk500::getTimeText(remaining / speed_ps)); newStatus.append(" remaining"); setStatus(newStatus); /* Write the 512 or less bytes of buffered data to the file */ if (remaining < 512) { destFile.write(buff, remaining); remaining = 0; break; } else { destFile.write(buff, 512); remaining -= 512; } } // Next cluster, if end of chain no more clusters follow cluster = protocol->sd().fatGet(cluster); if (protocol->sd().isEOC(cluster)) { break; } } } // If errors occur the deconstructor closes it as well... destFile.close(); // If cancelled, delete the file again (awh...) if (isCancelled()) { destFile.remove(); } }
void FileCreator(const std::string path, const std::string destFileName, const std::string outline ) { std::vector<std::string> files = util::listDir(path); if (files.size() <= 0)return; std::sort(std::begin(files), std::end(files)); /////////////////////////// HPDF_Doc pdf; pdf = HPDF_New(error_handler, NULL); if (!pdf) { std::cout<<"error: cannot create PdfDoc object"<<std::endl; return; } if (setjmp(env)) { HPDF_Free(pdf); return; } /* const char *font_name1; const char *font_name2; const char *font_name3; font_name1 = HPDF_LoadTTFontFromFile(pdf, "C:\\Windows\\Fonts\\Arial.ttf", HPDF_TRUE); font_name2 = HPDF_LoadTTFontFromFile(pdf, R"(C:\Windows\Fonts\simsunb.ttf)", HPDF_TRUE); font_name3 = HPDF_LoadTTFontFromFile2(pdf, "C:\\Windows\\Fonts\\simsun.ttc", 1, HPDF_TRUE); */ HPDF_Outline root; root = HPDF_CreateOutline(pdf, NULL, outline.c_str(), NULL); HPDF_Outline_SetOpened(root, HPDF_TRUE); HPDF_SetInfoAttr(pdf, HPDF_INFO_AUTHOR, config::AUTHOR); HPDF_SetInfoAttr(pdf, HPDF_INFO_TITLE, path.c_str()); HPDF_Font font; switch (config::LANG_TYPE) { case pdf::config::CN: HPDF_UseCNSFonts(pdf); HPDF_UseCNSEncodings(pdf); font = HPDF_GetFont(pdf, "SimHei", "GB-EUC-H"); // SimSun SimHei break; case pdf::config::TW: HPDF_UseCNTFonts(pdf); HPDF_UseCNTEncodings(pdf); font = HPDF_GetFont(pdf, "MingLiU", "ETen-B5-H"); break; default: font = HPDF_GetFont(pdf, "Helvetica", NULL); break; } /////////////////////////// std::string contents; std::vector<std::string> vec; for (std::string file : files) { contents = util::getFileContents(file); vec = util::split(contents, '\n'); fileWriter(pdf, root, font, file.substr(path.length()), vec); } /////////////////////////// std::string destFile(path); destFile.append("/"); destFile.append(destFileName); HPDF_SaveToFile(pdf, destFile.c_str()); HPDF_Free(pdf); }//end FileCreator()
/* Create an uncompressed version of the file on the local file system. * Note this will save zero-length files. */ int TskL01Extract::saveFile(const uint64_t fileId, const ArchivedFile &archivedFile) { try { // If a file with this id already exists we raise an error std::auto_ptr<TskFile> pFile(TskServices::Instance().getFileManager().getFile(fileId)); if (pFile.get() != NULL && pFile->exists()) { std::stringstream msg; msg << "File id " << fileId << " already exists."; throw TskFileException(msg.str()); } // Create a blank file Poco::Path destPath(TskUtilities::toUTF8(TskServices::Instance().getFileManager().getPath(fileId))); Poco::File destFile(destPath); destFile.createFile(); // Get data from archive if (archivedFile.size > 0) { Poco::FileOutputStream fos(destFile.path(), std::ios::binary); uint64_t chunkSize = ExtractChunkSize; if (archivedFile.size < ExtractChunkSize) { chunkSize = archivedFile.size; } Poco::SharedPtr<char, Poco::ReferenceCounter, ArrayReleasePolicy<char> > dataBuf(new char[chunkSize]); uint64_t accum = 0; ewf::libewf_error_t *ewfError = NULL; // Read and save data in chunks so that we only put <= ExtractChunkSize bytes on the heap at a time while (accum < archivedFile.size) { ssize_t bytesRead = ewf::libewf_file_entry_read_buffer(archivedFile.entry, dataBuf, chunkSize, &ewfError); if (bytesRead == -1) { std::stringstream logMessage; char errorString[512]; errorString[0] = '\0'; ewf::libewf_error_backtrace_sprint(ewfError, errorString, 512); logMessage << "TskL01Extract::saveFile - Error : " << errorString << std::endl; LOGERROR(logMessage.str()); return -1; } fos.write(dataBuf, bytesRead); accum += bytesRead; } fos.close(); } return 0; } catch (Poco::Exception& ex) { std::wstringstream msg; msg << L"TskL01Extract::saveFile - Error saving file from stream : " << ex.displayText().c_str(); LOGERROR(msg.str()); return -2; } }
void IpodCopyTracksJob::run() { if( !m_coll ) return; // destructed behind our back float totalSafeCapacity = m_coll.data()->totalCapacity() - m_coll.data()->capacityMargin(); QByteArray mountPoint = QFile::encodeName( m_coll.data()->mountPoint() ); QString collectionPrettyName = m_coll.data()->prettyName(); int trackCount = m_sources.size(); QString operationText; if( m_transcodingConfig.isJustCopy() ) operationText = i18np( "Transferring one track to %2", "Transferring %1 tracks to %2", trackCount, collectionPrettyName ); else operationText = i18np( "Transcoding one track to %2", "Transcoding %1 tracks to %2", trackCount, collectionPrettyName ); Amarok::Components::logger()->newProgressOperation( this, operationText, trackCount, this, SLOT(abort()) ); itdb_start_sync( m_coll.data()->m_itdb ); QMapIterator<Meta::TrackPtr, KUrl> it( m_sources ); while( it.hasNext() ) { if( m_aborted || !m_coll ) break; it.next(); Meta::TrackPtr track = it.key(); KUrl sourceUrl = it.value(); emit startDuplicateTrackSearch( track ); // wait for searching to finish: m_searchingForDuplicates.acquire( 1 ); if( m_duplicateTrack ) { trackProcessed( Duplicate, track, m_duplicateTrack ); continue; } if( !m_coll ) break; // destructed behind our back if( m_transcodingConfig.isJustCopy() // if not copying, we catch big files later && track->filesize() > totalSafeCapacity - m_coll.data()->usedCapacity() ) { // this is a best effort check, we do one definite one after the file is copied debug() << "Refusing to copy" << track->prettyUrl() << "to iPod: there are only" << totalSafeCapacity - m_coll.data()->usedCapacity() << "free bytes (not" << "counting a safety margin) on iPod and track has" << track->filesize() << "bytes."; trackProcessed( ExceededingSafeCapacity, track ); continue; } QString fileExtension; if( m_transcodingConfig.isJustCopy() ) fileExtension = track->type(); else fileExtension = Amarok::Components::transcodingController()->format( m_transcodingConfig.encoder() )->fileExtension(); if( !m_coll.data()->supportedFormats().contains( fileExtension ) ) { m_notPlayableFormats.insert( fileExtension ); trackProcessed( NotPlayable, track ); continue; } QByteArray fakeSrcName( "filename." ); // only for file extension fakeSrcName.append( QFile::encodeName( fileExtension ) ); /* determine destination filename; we cannot use ipodTrack because as it has no itdb * (and thus mountpoint) set */ GError *error = 0; gchar *destFilename = itdb_cp_get_dest_filename( 0, mountPoint, fakeSrcName, &error ); if( error ) { warning() << "Cannot construct iPod track filename:" << error->message; g_error_free( error ); error = 0; } if( !destFilename ) { trackProcessed( InternalError, track ); continue; } // start the physical copying KUrl destUrl = KUrl( QFile::decodeName( destFilename ) ); emit startCopyOrTranscodeJob( sourceUrl, destUrl ); // wait for copying to finish: m_copying.acquire( 1 ); /* fsync so that progress bar gives correct info and user doesnt remove the iPod * prematurely */ QFile destFile( QFile::decodeName( destFilename ) ); if( !destFile.exists() ) { debug() << destFile.fileName() << "does not exist even though we thought we copied it to iPod"; trackProcessed( CopyingFailed, track ); continue; } if( !m_coll ) break; // destructed behind our back if( m_coll.data()->usedCapacity() > totalSafeCapacity ) { debug() << "We exceeded total safe-to-use capacity on iPod (safe-to-use:" << totalSafeCapacity << "B, used:" << m_coll.data()->usedCapacity() << "): removing copied track from iPod"; destFile.remove(); trackProcessed( ExceededingSafeCapacity, track ); continue; } // fsync needs a file opened for writing, and without Apped it truncates files (?) if( !destFile.open( QIODevice::WriteOnly | QIODevice::Append ) ) { warning() << "Cannot open file copied to ipod (for writing):" << destFile.fileName() << ": removing it"; destFile.remove(); trackProcessed( InternalError, track ); continue; } if( destFile.size() ) fsync( destFile.handle() ); // should flush all kernel buffers to disk destFile.close(); // create a new track object by copying meta-data from existing one: IpodMeta::Track *ipodTrack = new IpodMeta::Track( track ); // tell the track it has been copied: bool accepted = ipodTrack->finalizeCopying( mountPoint, destFilename ); g_free( destFilename ); destFilename = 0; if( !accepted ) { debug() << "ipodTrack->finalizeCopying( destFilename ) returned false!"; delete ipodTrack; trackProcessed( InternalError, track ); continue; } if( !m_transcodingConfig.isJustCopy() ) { // we need to reread some metadata in case the file was transcoded Meta::FieldHash fields = Meta::Tag::readTags( destFile.fileName() ); ipodTrack->setBitrate( fields.value( Meta::valBitrate, 0 ).toInt() ); ipodTrack->setLength( fields.value( Meta::valLength, 0 ).toLongLong() ); ipodTrack->setSampleRate( fields.value( Meta::valSamplerate, 0 ).toInt() ); Amarok::FileType type = Amarok::FileType( fields.value( Meta::valFormat, 0 ).toInt() ); ipodTrack->setType( Amarok::FileTypeSupport::toString( type ) ); // we retain ReplayGain, tags etc - these shouldn't change; size is read // in finalizeCopying() } // add the track to collection if( !m_coll ) { delete ipodTrack; break; // we were waiting for copying, m_coll may got destoryed } Meta::TrackPtr newTrack = m_coll.data()->addTrack( ipodTrack ); if( !newTrack ) { destFile.remove(); trackProcessed( InternalError, track ); continue; } trackProcessed( Success, track, newTrack ); } if( m_coll ) itdb_stop_sync( m_coll.data()->m_itdb ); emit endProgressOperation( this ); int sourceSize = m_sources.size(); int successCount = m_sourceTrackStatus.count( Success ); int duplicateCount = m_sourceTrackStatus.count( Duplicate ); QString transferredText; if ( m_transcodingConfig.isJustCopy() ) transferredText = i18ncp( "%2 is collection name", "Transferred one track to %2.", "Transferred %1 tracks to %2.", successCount, collectionPrettyName ); else transferredText = i18ncp( "%2 is collection name", "Transcoded one track to %2.", "Transcoded %1 tracks to %2.", successCount, collectionPrettyName ); if( successCount == sourceSize ) { Amarok::Components::logger()->shortMessage( transferredText ); } else if( m_aborted ) { QString text = i18np( "Transfer aborted. Managed to transfer one track.", "Transfer aborted. Managed to transfer %1 tracks.", successCount ); Amarok::Components::logger()->longMessage( text ); } else if( successCount + duplicateCount == sourceSize ) { QString text = i18ncp( "%2 is the 'Transferred 123 tracks to Some collection.' message", "%2 One track was already there.", "%2 %1 tracks were already there.", duplicateCount, transferredText ); Amarok::Components::logger()->longMessage( text ); } else { // somethig more severe failed, notify user using a dialog emit displaySorryDialog(); } }
bool BackupTask::fullExport(const QString &destPath, QString &errorMessage) { int dbVersion = DefinitionHolder::DATABASE_VERSION; qint64 metadataOffset = 0; QMap<qint64, QString> fileOffset; QStringList contentFileList = MetadataEngine::getInstance() .getAllContentFiles().values(); //calc progress int progress = 0; int totalSteps = 0; totalSteps = 1 + contentFileList.size(); emit progressSignal(progress, totalSteps); QFile destFile(destPath); if (!destFile.open(QIODevice::WriteOnly)) { errorMessage = tr("Failed to open create file %1: %2") .arg(destPath).arg(destFile.errorString()); return false; } QDataStream out(&destFile); out << m_magicNumber; out << dbVersion; int placeHolderOffset = destFile.pos(); out << metadataOffset; //place holder //write database file fileOffset.insert(destFile.pos(), "database"); QFile dbFile(m_dbPath); if (!dbFile.open(QIODevice::ReadOnly)) { errorMessage = tr("Failed to open file %1: %2") .arg(m_dbPath).arg(dbFile.errorString()); return false; } while(!dbFile.atEnd()) { destFile.write(dbFile.read(m_fileBufSize)); } dbFile.close(); //update progress emit progressSignal(++progress, totalSteps); //write content files foreach (QString s, contentFileList) { fileOffset.insert(destFile.pos(), s); QFile file(m_filesDir + s); if (!file.open(QIODevice::ReadOnly)) { errorMessage = tr("Failed to open file %1: %2") .arg(m_filesDir + s).arg(file.errorString()); return false; } while(!file.atEnd()) { destFile.write(file.read(m_fileBufSize)); } file.close(); //update progress emit progressSignal(++progress, totalSteps); }
bool CloneThread::cloneFiles(const QStringList &absoluteSourceFiles, const QStringList &absoluteDestinationFiles, const quint64 totalSize) { if (absoluteSourceFiles.length() != absoluteDestinationFiles.length()) { mError = tr("Amount of source files not equals to amount of destination files"); qCritical() << "Error:" << mError; return false; } char buffer[BUFFER_SIZE]; quint64 totalProgress = 0; qint64 timeStart = QDateTime::currentMSecsSinceEpoch(); for (int i=0; !mTerminated && i<absoluteSourceFiles.length(); ++i) { QString srcFileName = absoluteSourceFiles.at(i); QString destFileName = absoluteDestinationFiles.at(i); qDebug() << "Cloning:" << srcFileName; QFile srcFile(srcFileName); QFile destFile(destFileName); if (!srcFile.exists()) { mError = tr("File not found: %1").arg(QDir::toNativeSeparators(srcFileName)); qCritical() << "Error:" << mError; return false; } QString destFilePath = destFileName.left(destFileName.lastIndexOf("/")); if (!QDir().mkpath(destFilePath)) { mError = tr("Impossible to create path: %1").arg(QDir::toNativeSeparators(destFilePath)); qCritical() << "Error:" << mError; return false; } if (!srcFile.open(QIODevice::ReadOnly)) { mError = tr("Impossible to open file: %1").arg(QDir::toNativeSeparators(srcFileName)); qCritical() << "Error:" << mError; return false; } if (!destFile.open(QIODevice::WriteOnly)) { mError = tr("Impossible to create file: %1").arg(QDir::toNativeSeparators(destFileName)); qCritical() << "Error:" << mError; return false; } quint64 fileProgress = 0; quint64 fileSize = srcFile.size(); while (!mTerminated && !srcFile.atEnd()) { qint64 bytes = srcFile.read(buffer, BUFFER_SIZE); if (bytes < 0) { mError = tr("Impossible to read file: %1").arg(QDir::toNativeSeparators(srcFileName)); qCritical() << "Error:" << mError; return false; } if (destFile.write(buffer, bytes) != bytes) { mError = tr("Impossible to write file: %1").arg(QDir::toNativeSeparators(destFileName)); qCritical() << "Error:" << mError; return false; } fileProgress += bytes; totalProgress += bytes; if (fileSize && totalSize) { qint64 curTime = QDateTime::currentMSecsSinceEpoch(); if (curTime > timeStart + 1000) { timeStart = curTime; emit OnProgressChanged(srcFileName, fileProgress * 100 / fileSize, totalProgress * 100 / totalSize); } } } srcFile.close(); destFile.close(); } return !mTerminated; }
void ReleaseDialog::release() { QString pwd = lineedit_pwd->text(); QString name = lineedit_name->text(); if(pwd.isEmpty() || name.isEmpty() || name.size() > 16) { QString prompt; prompt = QString("必须设置加密密码\n填写版本信息。"); if(name.size() > 16) prompt = QString("版本信息不能超过16个字符。"); QMessageBox box(QMessageBox::Information, "提示", prompt); box.setStandardButtons(QMessageBox::Ok); box.setButtonText(QMessageBox::Ok, "确定"); box.exec(); return; } ////name 最大16个字符 if(!setFilePath()) return; QDateTime start,end; getDateTime(start, end); QString jsonfilePath = getReadFilePath(start, end); ///读JSON下载资源 readJsonFile(jsonfilePath); ///打包 QStringList fileNames = getCurrentDirFiles(releasePath); QString destPath = QCoreApplication::applicationDirPath(); destPath.append("/ZIP/"); QDir dir(destPath); if(!dir.exists()) dir.mkpath(destPath); QString destName = currentDate.toString("yyyy-MM-dd_hh_mm_ss"); destName.append(".zip"); destPath.append(destName); QFile destFile(destPath); if(destFile.exists()) { } zipFile zf; QByteArray dest = destPath.toLocal8Bit(); zf = zipOpen(dest.data(), APPEND_STATUS_CREATE); if (zf == NULL) { return; } // LOKI_ON_BLOCK_EXIT(zipClose, zf, (const char *)NULL); for (int i=0; i<fileNames.size(); i++) { QString tempStr = fileNames.at(i); QString path = releasePath; path.remove("music"); QString temprel = path; QString deststr = tempStr.remove(temprel); if (!ZipAddFile(zf, deststr, fileNames.at(i), pwd, true)) //"default_yqc" { continue; } } int errclose = zipClose(zf, NULL); if (errclose != ZIP_OK) qDebug() << " zipClose ret : " << errclose; ///上传打包文件 QString url; CurlUpload *curlUpload = new CurlUpload(); bool ok = curlUpload->uploadYQDyun(destName, destPath, url); qDebug() << " upload yun : ok : " << ok; qDebug() << " zip name " << destName; qDebug() << " url " << url; /// post 表格数据 QDateTime time = QDateTime::currentDateTime(); QString timeStr = time.toString("yyyy-MM-dd-hh-mm-ss"); int version = time.toTime_t(); QString postStr = QString("name=%1&url=%2&time=%3&remark=%4&version=%5") .arg(name) .arg(url) .arg(timeStr) .arg(pwd) .arg(version); CurlUpload *curlDownlaod = new CurlUpload(); curlDownlaod->postJson(postStr); return; }