/** Allows to open attachment item using default application registerd for given document type
        in the OS.
    */
    void Open() const
      {
      const QString title(tr("Open attachment..."));
      TFileAttachmentWidget* owner = GetOwner();

      QString fileName(GetDisplayedFileName());
      /// FIXME - actually each created temp file should be registered in the main app to be deleted at exit.
      QTemporaryFile tempFile(QDir::tempPath() + "/XXXXXX." + fileName);
      tempFile.setAutoRemove(false);
      if(tempFile.open() == false)
        {
        QMessageBox::warning(owner, title, tr("Cannot open temporary file to store attachment: ") +
            fileName);
        return;
        }

      QFileInfo tfi(tempFile);

      if(owner->SaveAttachmentItem(this, tfi, false))
        {
        QUrl url(QUrl::fromLocalFile(tfi.absoluteFilePath()));
        if(QDesktopServices::openUrl(url) == false)
          {
          /// Report a message if opening failed.
          QMessageBox::warning(owner, title, tr("Cannot open attachment using its default application: ") +
             fileName);
          }
        }

      tempFile.close();
      }
void FileShareProtocol::paste(const QString &text,
                              ContentType /* ct */,
                              const QString &username,
                              const QString & /* comment */,
                              const QString &description)
{
    // Write out temp XML file
    QTemporaryFile tempFile(m_settings->path + QLatin1Char('/') + QLatin1String(tempPatternC));
    tempFile.setAutoRemove(false);
    if (!tempFile.open()) {
        const QString msg = tr("Unable to open a file for writing in %1: %2").arg(m_settings->path, tempFile.errorString());
        Core::ICore::instance()->messageManager()->printToOutputPanePopup(msg);
        return;
    }
    // Flat text sections embedded into pasterElement
    QXmlStreamWriter writer(&tempFile);
    writer.writeStartDocument();
    writer.writeStartElement(QLatin1String(pasterElementC));

    writer.writeTextElement(QLatin1String(userElementC), username);
    writer.writeTextElement(QLatin1String(descriptionElementC), description);
    writer.writeTextElement(QLatin1String(textElementC), text);

    writer.writeEndElement();
    writer.writeEndDocument();
    tempFile.close();

    const QString msg = tr("Pasted: %1").arg(tempFile.fileName());
    Core::ICore::instance()->messageManager()->printToOutputPanePopup(msg);
}
示例#3
0
QString getVerboseGccIncludePath(bool *ok)
{
  *ok = false;
  ///Create temp file
  KTempFile tempFile(locateLocal("tmp", "kdevelop_temp"), ".cpp");
  tempFile.setAutoDelete(true);
  if( tempFile.status() != 0 ) 
    return QString();//Failed to create temp file
  
  QString path = tempFile.name();
  QFileInfo pathInfo( path );

  char fileText[] = "//This source-file is empty";
  fwrite(fileText, strlen(fileText), 1, tempFile.fstream() );
  tempFile.close();
  
  BlockingKProcess proc;
  proc.setUseShell(true);
  proc.setWorkingDirectory(pathInfo.dir(true).path());
  proc << "gcc -v " + pathInfo.fileName() + " 2>&1";
  if ( !proc.start(KProcess::NotifyOnExit, KProcess::Stdout) ) {
    kdWarning(9007) << "Couldn't start gcc" << endl;
    *ok = false;
    return QString();
  }
  *ok = true;
  return proc.stdOut();
}
示例#4
0
bool Utils::checkCacheDir(QString dirPath){
    qDebug() << "checkCacheDir: " + dirPath;

    if (dirPath.isNull() || dirPath.isEmpty()){
        qDebug() << "checkCacheDir: dirPath is empty";
        return false;
    }

    QDir dir(dirPath);
    if (!dir.exists()){
        qDebug() << "checkCacheDir: dirPath does not exist, will try to create";
        QString dirName = dir.dirName();
        if (!dir.cdUp()){
            qDebug() << "checkCacheDir: dirPath's parent does not exist";
            return false;
        }
        if (!dir.mkdir(dirName)){
            qDebug() << "checkCacheDir: can not create dirPath";
            return false;
        }
    }
    QFile tempFile(dirPath + "/.vk-music-temp");
    if (!tempFile.open(QIODevice::ReadWrite)){
        qDebug() << "checkCacheDir: dirPath is not writable";
        return false;
    }
    tempFile.close();
    qDebug() << "checkCacheDir: dirPath is OK";
    return true;
}
示例#5
0
extern void make_tempfile( producer_qimage self, const char *xml )
{
	// Generate a temporary file for the svg
	QTemporaryFile tempFile( "mlt.XXXXXX" );

	tempFile.setAutoRemove( false );
	if ( tempFile.open() )
	{
		// Write the svg into the temp file
		char *fullname = tempFile.fileName().toUtf8().data();

		// Strip leading crap
		while ( xml[0] != '<' )
			xml++;

		qint64 remaining_bytes = strlen( xml );
		while ( remaining_bytes > 0 )
			remaining_bytes -= tempFile.write( xml + strlen( xml ) - remaining_bytes, remaining_bytes );
		tempFile.close();

		mlt_properties_set( self->filenames, "0", fullname );

		mlt_properties_set_data( MLT_PRODUCER_PROPERTIES( &self->parent ), "__temporary_file__",
			fullname, 0, ( mlt_destructor )unlink, NULL );
	}
}
示例#6
0
void JpegEncoder::FillBufferDone(OMX_U8* pBuffer, OMX_U32 size)
{

#if JPEG_ENCODER_DUMP_INPUT_AND_OUTPUT
    
    char path[50];
    snprintf(path, sizeof(path), "%s/JEO_%d.jpg", DUMP_DIR ,eOutputCount);

    PRINTF("\nrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr");
    
    SkFILEWStream tempFile(path);
    if (tempFile.write(pBuffer, size) == false)
        PRINTF("\nWriting to %s failed\n", path);
    else
        PRINTF("\nWriting to %s succeeded\n", path);

    eOutputCount++;
    PRINTF("\nrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr");
#endif

    iLastState = iState;
    iState = STATE_FILL_BUFFER_DONE_CALLED;
    jpegSize = size;
   // sem_post(semaphore) ;
}
示例#7
0
bool ClassType::loadString(const std::string& config)
{
  std::ofstream tempFile;
  std::string fn;
  if (OSS::boost_temp_file(fn))
  {
    std::ofstream tempFile(fn.c_str());
    if (tempFile.is_open())
    {
      tempFile.write(config.data(), config.size());
      tempFile.close();
      bool ok = load(fn);
      boost::filesystem::remove(fn);
      
      if (!ok)
      {
        OSS_LOG_ERROR("ClassType::loadString - Unable to load " << fn.c_str() << " for reading.");
      }
      return ok;
    }
    else
    {
      OSS_LOG_ERROR("ClassType::loadString - Unable to open " << fn.c_str() << " for writing.");
    }
  }
  else
  {
    OSS_LOG_ERROR("ClassType::loadString - Unable to generate new temp filename");
  }
  return false;
}
示例#8
0
bool DictModel::save()
{
    char* name = NULL;
    FcitxXDGMakeDirUser("kkc");
    FcitxXDGGetFileUserWithPrefix("kkc", "dictionary_list", NULL, &name);
    QString fileName = QString::fromLocal8Bit(name);
    QTemporaryFile tempFile(fileName);
    free(name);
    if (!tempFile.open()) {
        return false;
    }

    typedef QMap<QString, QString> DictType;

    Q_FOREACH(const DictType& dict, m_dicts) {
        boolean first = true;
        Q_FOREACH(const QString& key, dict.keys()) {
            if (first) {
                first = false;
            } else {
                tempFile.write(",");
            }
            tempFile.write(key.toUtf8());
            tempFile.write("=");
            tempFile.write(dict[key].toUtf8());
        }
        tempFile.write("\n");
    }
示例#9
0
static QString CreateTempFile(QuaZip& zip, QString zipFilename)
{
	if (!zip.setCurrentFile(zipFilename))
	{
		ccLog::Warning(QString("[Photoscan] Failed to locate '%1' in the Photoscan archive").arg(zipFilename));
		return QString();
	}

	//decompress the file
	QuaZipFile zipFile(&zip);
	if (!zipFile.open(QFile::ReadOnly))
	{
		ccLog::Warning(QString("[Photoscan] Failed to extract '%1' from Photoscan archive").arg(zipFilename));
		return QString();
	}

	QDir tempDir = QDir::temp();
	QString tempFilename = tempDir.absoluteFilePath(zipFilename);
	QFile tempFile(tempFilename);
	if (!tempFile.open(QFile::WriteOnly))
	{
		ccLog::Warning(QString("[Photoscan] Failed to create temp file '%1'").arg(tempFilename));
		return QString();
	}
	tempFile.write(zipFile.readAll());
	tempFile.close();

	return tempFilename;
}
示例#10
0
void* PreviewDlg::CommandThread::Entry() {
	cxExecute exec(m_env);
	//exec.SetDebugLogging(true);

	int resultCode = exec.Execute(m_command, m_input);

	// Write the output	to file
	if (!m_isTerminated && resultCode != -1) {
		wxFile tempFile(m_outputPath, wxFile::write);

		if (tempFile.IsOpened()) {
			vector<char> output;
			output.swap(exec.GetOutput());

			if (!output.empty()) {
				PreviewDlg::InsertBase(output, m_truePath);
				tempFile.Write(&*output.begin(), output.size());
			}
		}
	}

	if (m_isTerminated) return NULL;

	// Notify parent that the command is done
	wxProcessEvent event(99, 0, resultCode);
	m_parent.AddPendingEvent(event);

	return NULL;
}
示例#11
0
bool copyFileAtomic(const QString& source, const QString& target)
{
	bool success = false;
	if ((source.isEmpty()) || (target.isEmpty()))
		return false;
	if (source == target)
		return false;
	QFile srcFile(source);
	QString tempFileName;
	QTemporaryFile tempFile(target + "_XXXXXX");
	if (srcFile.open(QIODevice::ReadOnly))
	{
		if (tempFile.open())
		{
			tempFileName = tempFile.fileName();
			success  = copyData(srcFile, tempFile);
			success &= (srcFile.error() == QFile::NoError && tempFile.error() == QFile::NoError);
			tempFile.close();
		}
		srcFile.close();
	}
	if (success)
	{
		if (QFile::exists(target))
			success = QFile::remove(target);
		if (success)
		{
			success = QFile::rename(tempFileName, target);
			// if rename failed tempFileName should not be removed
			// Note : on Windows QFile::rename() may not remove tempFileName :S
			tempFile.setAutoRemove(success);
		}
	}
	return success;
}
示例#12
0
文件: entry.c 项目: Luoben/ctags
extern void openTagFile (void)
{
	setDefaultTagFileName ();
	TagsToStdout = isDestinationStdout ();

	if (TagFile.vLine == NULL)
		TagFile.vLine = vStringNew ();

	/*  Open the tags file.
	 */
	if (TagsToStdout)
		/* Open a tempfile with read and write mode. Read mode is used when
		 * write the result to stdout. */
		TagFile.fp = tempFile ("w+", &TagFile.name);
	else
	{
		boolean fileExists;

		TagFile.name = eStrdup (Option.tagFileName);
		fileExists = doesFileExist (TagFile.name);
		if (fileExists  &&  ! isTagFile (TagFile.name))
			error (FATAL,
			  "\"%s\" doesn't look like a tag file; I refuse to overwrite it.",
				  TagFile.name);

		if (Option.etags)
		{
			if (Option.append  &&  fileExists)
				TagFile.fp = fopen (TagFile.name, "a+b");
			else
				TagFile.fp = fopen (TagFile.name, "w+b");
		}
		else
		{
			if (Option.append  &&  fileExists)
			{
				TagFile.fp = fopen (TagFile.name, "r+");
				if (TagFile.fp != NULL)
				{
					TagFile.numTags.prev = updatePseudoTags (TagFile.fp);
					fclose (TagFile.fp);
					TagFile.fp = fopen (TagFile.name, "a+");
				}
			}
			else
			{
				TagFile.fp = fopen (TagFile.name, "w");
				if (TagFile.fp != NULL)
					addPseudoTags ();
			}
		}
		if (TagFile.fp == NULL)
			error (FATAL | PERROR, "cannot open tag file");
	}
	if (TagsToStdout)
		TagFile.directory = eStrdup (CurrentDirectory);
	else
		TagFile.directory = absoluteDirname (TagFile.name);
}
示例#13
0
terrama2::core::DataSetSeries terrama2::core::DataAccessorDcpToa5::getSeries(const std::string& uri,
        const terrama2::core::Filter& filter,
        terrama2::core::DataSetPtr dataSet) const

{
    std::string mask = getMask(dataSet);
    std::string folder = getFolder(dataSet);

    QTemporaryDir tempBaseDir;
    if(!tempBaseDir.isValid())
    {
        QString errMsg = QObject::tr("Can't create temporary folder.");
        TERRAMA2_LOG_ERROR() << errMsg;
        throw DataAccessException() << ErrorDescription(errMsg);
    }

    QDir tempDir(tempBaseDir.path());
    tempDir.mkdir(QString::fromStdString(folder));
    tempDir.cd(QString::fromStdString(folder));

    QUrl url((uri+"/"+folder+"/"+mask).c_str());
    QFileInfo originalInfo(url.path());

    QFile file(url.path());
    QFile tempFile(tempDir.path()+"/"+originalInfo.fileName());
    if(!file.open(QIODevice::ReadOnly))
    {
        QString errMsg = QObject::tr("Can't open file: dataset %1.").arg(dataSet->id);
        TERRAMA2_LOG_ERROR() << errMsg;
        throw DataAccessException() << ErrorDescription(errMsg);
    }

    if(!tempFile.open(QIODevice::ReadWrite))
    {
        QString errMsg = QObject::tr("Can't open temporary file: dataset %1.").arg(dataSet->id);
        TERRAMA2_LOG_ERROR() << errMsg;
        throw DataAccessException() << ErrorDescription(errMsg);
    }

    file.readLine();//ignore first line
    tempFile.write(file.readLine()); //headers line

    //ignore third and fourth lines
    file.readLine();
    file.readLine();

    //read all file
    tempFile.write(file.readAll()); //headers line

    //update file path
    std::string tempUri = "file://"+tempBaseDir.path().toStdString();

    file.close();
    tempFile.close();

    auto dataSeries = terrama2::core::DataAccessorFile::getSeries(tempUri, filter, dataSet);

    return dataSeries;
}
示例#14
0
HtmlDialog::HtmlDialog(wxWindow* parent, const OptionDict& options) 
: wxDialog(parent, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxDEFAULT_DIALOG_STYLE|wxRESIZE_BORDER),
  m_optionDict(options) {
	// Set the dialog title
	const wxString title = options.GetOption(wxT("title"));
	SetTitle(options.GetOption(wxT("title")));

	// IE Control
	m_ie = new wxIEHtmlWin(this, ID_MSHTML);

	// Load html from file
	if (options.HasOption(wxT("html-from-file")))
	{
		wxString htmlFile = options.GetOption(wxT("html-from-file"));
#ifdef __WXMSW__
		if (!htmlFile.empty()) {
			htmlFile = CygwinPathToWin(htmlFile);
		}
#endif // __WXMSW__
		
		// We need an absolute path
		wxFileName path(htmlFile);
		path.MakeAbsolute();

		m_ie->LoadUrl(path.GetFullPath());
	}
	else { // Load html for stdin
		// Create temp file
		m_tempPath = wxFileName::CreateTempFileName(wxEmptyString) + wxT(".html");
		wxFFile tempFile(m_tempPath, wxT("wb"));
		if (!tempFile.IsOpened()) {
			Close();
			return;
		}
		
		// Load html from stdin to temp file
		int c;
		FILE* fp = tempFile.fp();
		while ((c = getc(stdin)) != EOF) putc(c, fp);
		tempFile.Close();

		m_ie->LoadUrl(m_tempPath);
	}

	// Create layout
	wxSizer* mainSizer = new wxBoxSizer(wxVERTICAL);
	mainSizer->Add(m_ie, 1, wxEXPAND);
	SetSizer(mainSizer);

	int width;
	int height;
	if (options.GetIntegerOption(wxT("width"), width) &&
		options.GetIntegerOption(wxT("height"), height)) {
		SetSize(width, height);
	}

	Centre();
	Show();
}
示例#15
0
std::vector<int>* MetisWrapper::cluster(const MatrixWrapper& graph, int numClusters)
{
	if (graph.getRows() != graph.getCols()) {
		assert(graph.getRows() != graph.getCols());
	}

	int nodes = graph.getRows();
	int edges = graph.countNonZeros();
	std::ofstream tempFile(MetisWrapper::TEMP_METIS_FILENAME.c_str());
	tempFile<<nodes<<" "<<(int) (edges / 2)<<" "<<1<<"\n";

	for (int node = 0; node < nodes; ++node) {
		bool firstNeighbor = true;

		for (int neighbor = 0; neighbor < nodes; neighbor++) {
			if (graph.get(node, neighbor) > 0) {
				if (graph.get(neighbor, node) != graph.get(node, neighbor)) {
					assert(graph.get(neighbor, node) != graph.get(node, neighbor));
				}

				if (firstNeighbor) {
					firstNeighbor = false;
				}

				else {
					tempFile<<" ";
				}

				tempFile<<(neighbor + 1)<<" "<<(int) graph.get(node, neighbor);
			}
		}

		tempFile<<"\n";
	}

	tempFile.close();
	std::string nclusters = convertToString(numClusters);
	char* command [3]= {&MetisWrapper::METIS_COMMAND[0], &MetisWrapper::TEMP_METIS_FILENAME[0], &nclusters[0]};
	std::string output = MetisWrapper::run(3, command);
	std::ifstream resultFile((MetisWrapper::TEMP_METIS_FILENAME + ".part." + convertToString(numClusters)).c_str());
	/*
	 * if (resultFile no existe)
	 * poner error de que no se genero el archivo de salida
	 *
	 */
	std::vector<int> *result = new std::vector<int>(nodes);
	std::string line;
	int node = 0;

	while(getline(resultFile, line, '\n')) {
		int cluster = atoi(line.c_str());
		(*result)[node] = cluster;
		++node;
	}

	resultFile.close();
	return result;
}
示例#16
0
void InfosProduitDialog::on_listGaranties_itemDoubleClicked(QListWidgetItem *item)
{
    QByteArray contentFile = garantiePDF.value(item->text());
    QFile tempFile(QDir::tempPath()+"/"+item->text());
    tempFile.open(QFile::WriteOnly);
    tempFile.write(contentFile);
    tempFile.close();
    QDesktopServices::openUrl(QUrl("file:///"+tempFile.fileName()));
}
示例#17
0
/*!
 * Creates a temporary file in the directory of an original file.
 * \param originalPath Absolute path that is used as a base for generating
 * the temporary file.
 * \return Path of the created file, or an empty string if creating the
 * file fails. The returned value is a copy, so for uses where it's assigned
 * to a variable, it need not be const. For cases where it's passed as a
 * parameter, it need not be const because references to non-const will
 * not bind to function return values, because they are rvalues. When
 * C++0x brings rvalue references, the value should not be const in order
 * to allow rvalue references to bind to it and thus enable moving from it.
 */
static QString createTempFile(const QString &originalPath)
{
    QString returnValue;
    QTemporaryFile tempFile(originalPath);
    if (tempFile.open()) {
        tempFile.setAutoRemove(false);
        returnValue = tempFile.fileName();
    }
    return returnValue;
}
示例#18
0
//-----------------------------------------------------------------------------
//! Flush the settings to file
//-----------------------------------------------------------------------------
void tSettingsFileManager::Synchronize()
{
    //DbgPrintf( "tSettingsFileManager::Synchronize()" );

    // No longer copy from the temp file because we have just updated the Settings.ini file and
    // want that to take effect after the restart
    if ( m_syncStopped )
    {
        return;
    }

    //DbgPrintf("tSettingsFileManager::Synchronize");
    NAVICO_RECORD_LOCAL_TIME( s_ProfSync );
    
    tQWriteLocker lock(&m_Lock);
    m_syncTimerRunning = false;
    lock.unlock();

    m_lastSyncTime.Reset();

#ifdef Q_OS_LINUX
    // Lock temp file.  This is the lock mechanism that QSettings uses. 
    // It makes sure that app cant write file during the copy operation
    // QFile::copy uses qrand to form a unique intermediate filename. 
    // This is seeded from thread data which seg faults when called 
    // during application shutdown. Using tFile instead.
    tFile tempFile( tPath::SettingsIniTmpFile() );
    tempFile.open( QIODevice::ReadOnly | QIODevice::Unbuffered );
    struct flock fl;
    fl.l_whence = SEEK_SET;
    fl.l_start = 0;
    fl.l_len = 0; // zero size locks till EOF
    fl.l_type = F_WRLCK;
    fcntl( tempFile.handle(), F_SETLKW, &fl );

    // First find the real path if the settings.ini file is symbolic link
    QString settingsPath = tFile::symLinkTarget( tPath::SettingsIniFile() ); 
    if ( settingsPath.isEmpty() )
    {
        settingsPath = tPath::SettingsIniFile();
    }

    // Copy temp to the copy file in the persistent file system 
    QString copyFilePath = settingsPath;
    copyFilePath.append( ".copy" );

    tFile::remove( copyFilePath );
    tempFile.copy( copyFilePath ); // tFile::copy Flushes copied file to disk
    tempFile.close(); // this unlocks the file lock
    
    // Rename the copyed file back to settings.ini file (for atomic write)
    rename( copyFilePath.toAscii().constData(), settingsPath.toAscii().constData() );

#endif // Q_OS_LINUX
}
bool
GenericMapHeader::save( const char* filename, bool updateCreationTime )
{
   int un_res = unlink( filename );
   if ( un_res == 0 ) {
      mc2dbg << "[GMH]: Removed " << MC2CITE( filename ) << endl;
   } else {
      if ( errno == ENOENT ) {
         // Ok. No file exists
      } else {
         mc2log << error << "[GMH]::save could not remove "
                << filename << endl;
         return false;
      }
   }
   
   MC2String dirname = STLStringUtility::dirname( filename );
   
   char tempFilename[64];
   sprintf( tempFilename, "GMHsave0x%x_", m_mapID );
   TempFile tempFile( tempFilename, dirname, filename );

   if ( ! tempFile.ok() ) { 
      mc2log << error << "In GenericMapHeader::save(). " << endl;
      return false;
   }

   mc2dbg << "[GMH]: Writing to temp file " 
          <<  MC2CITE( tempFile.getTempFilename() ) << endl;
   

   m_updateCreationTime = updateCreationTime;
   bool retVal = internalSave( tempFile.getFD() );

   // Unfortunately internalSave does not return false
   // if the disk is full....
   if ( retVal ) {
      // Chmod the file
      if ( fchmod( tempFile.getFD(), S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH ) == -1 ) {
         mc2dbg << "[GMH]: Failed to chmod file. Error: " 
                << strerror( errno ) << endl;
      }
   }  else {
      mc2log << error << "[GMH]::save error when saving - removing "
             << tempFile.getTempFilename() << endl;

      tempFile.setFailed( true );
   }


   return retVal;
}
QgsRasterLayer* QgsSentDataSourceBuilder::rasterLayerFromSentRDS( const QDomElement& sentRDSElem, QList<QTemporaryFile*>& filesToRemove, QList<QgsMapLayer*>& layersToRemove ) const
{
  QgsMSDebugMsg( "Entering" );
  QString tempFilePath = createTempFile();
  if ( tempFilePath.isEmpty() )
  {
    return 0;
  }
  QFile tempFile( tempFilePath );

  QTemporaryFile* tmpFile = new QTemporaryFile();

  QString encoding = sentRDSElem.attribute( "encoding" );

  if ( encoding == "base64" )
  {
    if ( tmpFile->open() )
    {
      QByteArray binaryContent = QByteArray::fromBase64( sentRDSElem.text().toAscii() );
      QDataStream ds( tmpFile );
      ds.writeRawData( binaryContent.data(), binaryContent.length() );
    }
    else
    {
      delete tmpFile;
      return 0;
    }

  }
  else //assume text (e.g. ascii grid)
  {
    if ( tmpFile->open() )
    {
      QTextStream tempFileStream( tmpFile );
      tempFileStream << sentRDSElem.text();
    }
    else
    {
      delete tmpFile;
      return 0;
    }
  }

  QgsMSDebugMsg( "TempFilePath is: " + tempFilePath );
  tmpFile->close();

  QgsRasterLayer* rl = new QgsRasterLayer( tmpFile->fileName(), layerNameFromUri( tmpFile->fileName() ) );
  filesToRemove.push_back( tmpFile ); //make sure the temporary file gets deleted after each request
  layersToRemove.push_back( rl ); //make sure the layer gets deleted after each request
  return rl;
}
示例#21
0
bool DBThread::testWritable(QString path)const
{
    QFile tempFile(path+"/tempfile"); //test if we can write here...
    if(!tempFile.open(QFile::WriteOnly))
    {
        qDebug()<<"Could not write to: "+path+"/tempfile";
        return false;
    }
    if(!tempFile.remove()){
        qDebug()<<"Could not remove file: "+path+"/tempfile";;
        return false;
    }
    return true;
}
示例#22
0
//--------------------------------------------------------------------------
bool HoneDumpcap::OpenCaptureFile(void)
{
	const QString timestamp = QDateTime::currentDateTime().toString("yyyyMMddhhmmss");
	QString filename;

	if (m_captureFileName.isEmpty()) {
		// Format temporary file name
		filename = QString("%1/hone_dumpcap_%2_XXXXXX.pcapng").arg(QDir::tempPath(), timestamp);
		QTemporaryFile tempFile(filename);
		if (!tempFile.open()) {
			return LogError(QString("Cannot create temporary file with template %1: %2").arg(filename, m_captureFile.errorString()));
		}
		filename = tempFile.fileName();
		tempFile.close();
	} else {
		// Format file name
		if (m_autoRotateFiles) {
			QFileInfo fileInfo(m_captureFileName);
			filename = QString("%2/%3_%1_%4.%5").arg(m_captureFileCount).arg(fileInfo.filePath(),
					fileInfo.completeBaseName(), timestamp, fileInfo.suffix());
		} else {
			filename = m_captureFileName;
		}
	}

	m_captureFile.setFileName(filename);
	if (!m_captureFile.open(QIODevice::ReadWrite | QIODevice::Truncate | QIODevice::Unbuffered)) {
		return LogError(QString("Cannot open %1 for writing: %2").arg(filename, m_captureFile.errorString()));
	}

	m_captureFileNames.enqueue(filename);
	if (m_autoRotateFileCount) {
		while (m_captureFileNames.size() > static_cast<qint32>(m_autoRotateFileCount)) {
			const QString removeFilename = m_captureFileNames.dequeue();
			if (!QFile::remove(removeFilename)) {
				return LogError(QString("Cannot remove %1").arg(removeFilename));
			}
		}
	}

	m_captureFile.flush();
	m_captureFileCount++;
	m_captureFileSize = 0;
	if (m_parentPid.isEmpty()) {
		Log(QString("File: %1").arg(filename));
	} else {
		WriteCommand('F', filename);
	}
	return true;
}
示例#23
0
void tst_QPluginLoader::checkingStubsFromDifferentDrives()
{
#if defined(Q_OS_SYMBIAN)

    // This test needs C-drive + some additional drive (driveForStubs)

    const QString driveForStubs("E:/");// != "C:/"
    const QString stubDir("system/temp/stubtest/");
    const QString stubName("dummyStub.qtplugin");
    const QString fullStubFileName(stubDir + stubName);
    QDir dir(driveForStubs);
    bool test1(false); bool test2(false);

    // initial clean up
    QFile::remove(driveForStubs + fullStubFileName);
    dir.rmdir(driveForStubs + stubDir);

    // create a stub dir and do stub drive check
    if (!dir.mkpath(stubDir))
        QSKIP("Required drive not available for this test", SkipSingle);

    {// test without stub, should not be found
    QPluginLoader loader("C:/" + fullStubFileName);
    test1 = !loader.fileName().length();
    }

    // create a stub to defined drive
    QFile tempFile(driveForStubs + fullStubFileName);
    tempFile.open(QIODevice::ReadWrite);
    QFileInfo fileInfo(tempFile);

    {// now should be found even tried to find from C:
    QPluginLoader loader("C:/" + fullStubFileName);
    test2 = (loader.fileName() == fileInfo.absoluteFilePath());
    }

    // clean up
    tempFile.close();
    if (!QFile::remove(driveForStubs + fullStubFileName))
        QWARN("Could not remove stub file");
    if (!dir.rmdir(driveForStubs + stubDir))
        QWARN("Could not remove stub directory");

    // test after cleanup
    QVERIFY(test1);
    QVERIFY(test2);

#endif//Q_OS_SYMBIAN
}
示例#24
0
void CSoftDownloadThread::loadPercent(long lDownLoadByte, int totalBytes)
{
    //创建零时文件,记录当前下载数据
    QString temp = CMisc::getFileTemporary(m_pDesPath);
    QTemporaryFile tempFile(temp);
    tempFile.setAutoRemove(false);
    if(tempFile.open())
    {
        QDataStream out(&tempFile);
        out.setVersion(QDataStream::Qt_5_3);
        out << m_pSrcPath << lDownLoadByte << totalBytes;
        tempFile.close();
    }
    emit downloadPercent(m_pSoftKey, lDownLoadByte, totalBytes);
}
示例#25
0
void ksFileLoader::loadFile(string filePath){

    files.clear();
    fileNames.clear();
    fileBaseNames.clear();
    fileExtension.clear();
    fileSizes.clear();
    
    directory.listDir(filePath);
	directory.sort();

    files.assign(directory.size(), ofFile());
    
    if(!directory.size()){
		ksLog("Error: The directory %s is empty", filePath.c_str());
	}

	for (int i = 0; i < (int)directory.size(); ++i)
	{
		/* code */
//		cout<<"File num : " <<i<<endl;
//		cout<<"   getPath = "<<directory.getPath(i)<<endl;

		ofFile tempFile(directory.getPath(i));
        string tempFileName = tempFile.getFileName();
        string tempExtension = tempFile.getExtension();
        string tempFileBaseName = tempFile.getBaseName();
        float tempFileSize = tempFile.getSize()/1024/1024;
#ifdef KS_FILELOADER_DEBUG 
		cout<<"file Name: "<<tempFile.getFileName()<<endl;
		cout<<"file Size: "<<tempFile.getSize()<<endl;
#endif
		files.push_back(tempFile);
		fileNames.push_back(tempFileName);
        fileBaseNames.push_back(tempFileBaseName);
        fileExtension.push_back(tempExtension);
		fileSizes.push_back(tempFileSize);

		//files.push_back(tempFile);
	}

#ifdef KS_FILELOADER_DEBUG 
	//    cout<<"directory file[0] Name: " << directory.getFile(1).getFileName()<<endl;
	cout<<endl<<endl<<"directory Size: "<<directory.getFiles().size()<<endl;
#endif


}
bool initializeWithFile(const FilePath& filePath,
                        int width,
                        int height,
                        bool displayListon,
                        DeviceContext* pDC)
{
   // initialize file info
   if (filePath.empty())
      pDC->targetPath = tempFile("png");
   else
      pDC->targetPath = filePath;
   pDC->width = width;
   pDC->height = height;

   return true;
}
示例#27
0
void ViewManager::startDrag()
{
    // Get the list of all the selected addressees
    KABC::Addressee::List addrList;
    const QStringList uidList = selectedUids();
    if(uidList.isEmpty())
        return;

    kdDebug(5720) << "ViewManager::startDrag: starting to drag" << endl;

    QStringList::ConstIterator it;
    for(it = uidList.begin(); it != uidList.end(); ++it)
        addrList.append(mCore->addressBook()->findByUid(*it));

    KMultipleDrag *drag = new KMultipleDrag(this);

    KABC::VCardConverter converter;
    QString vcards = converter.createVCards(addrList);

    // Best text representation is given by textdrag, so it must be first
    drag->addDragObject(new QTextDrag(AddresseeUtil::addresseesToEmails(addrList), this));
    drag->addDragObject(new KVCardDrag(vcards, this));

    KTempDir tempDir;
    // can't set tempDir to autoDelete, in case of dropping on the desktop, the copy is async...
    if(tempDir.status() == 0)
    {
        QString fileName;
        if(addrList.count() == 1)
            fileName = addrList[ 0 ].givenName() + "_" + addrList[ 0 ].familyName() + ".vcf";
        else
            fileName = "contacts.vcf";

        QFile tempFile(tempDir.name() + "/" + fileName);
        if(tempFile.open(IO_WriteOnly))
        {
            tempFile.writeBlock(vcards.utf8());
            tempFile.close();

            KURLDrag *urlDrag = new KURLDrag(KURL(tempFile.name()), this);
            drag->addDragObject(urlDrag);
        }
    }

    drag->setPixmap(KGlobal::iconLoader()->loadIcon("vcard", KIcon::Desktop));
    drag->dragCopy();
}
示例#28
0
bool Block::EncryptFile(Stream &stream, const BinaryString &key, const BinaryString &iv, BinaryString &digest, String *newFileName)
{
	String tempFileName = File::TempName();
	File tempFile(tempFileName, File::Truncate);
	
	Aes cipher(&tempFile);
	cipher.setEncryptionKey(key);
	cipher.setInitializationVector(iv);
	cipher.write(stream);
	cipher.close();
	
	String fileName = Cache::Instance->move(tempFileName);
	if(newFileName) *newFileName = fileName;
	
	File file(fileName, File::Read);
	return Block::ProcessFile(file, digest);
}
std::string FSLSLBridgeScriptCallback::prepUploadFile()
{
	std::string fName = gDirUtilp->getExpandedFilename(LL_PATH_FS_RESOURCES, UPLOAD_SCRIPT_1_7);
	std::string fNew = gDirUtilp->getExpandedFilename(LL_PATH_CACHE,UPLOAD_SCRIPT_1_7);

	//open script text file
	typedef std::istream_iterator<char> istream_iterator;
	std::ifstream file(fName.c_str());

	typedef std::ostream_iterator<char> ostream_iterator;
	std::ofstream tempFile(fNew.c_str());
	
	file >> std::noskipws;
	std::copy(istream_iterator(file), istream_iterator(), ostream_iterator(tempFile));

	return fNew;
}
示例#30
-1
文件: entry.c 项目: mapad/ctags
/*  Replacement for missing library function.
 */
static int replacementTruncate (const char *const name, const long size)
{
	char *tempName = NULL;
	FILE *fp = tempFile ("w", &tempName);
	fclose (fp);
	copyFile (name, tempName, size);
	copyFile (tempName, name, WHOLE_FILE);
	remove (tempName);
	eFree (tempName);

	return 0;
}