示例#1
0
voidpf ZCALLBACK qiodevice_open_file_func (
   voidpf opaque UNUSED,
   voidpf file,
   int mode)
{
    QIODevice *iodevice = reinterpret_cast<QIODevice*>(file);
    if ((mode & ZLIB_FILEFUNC_MODE_READWRITEFILTER)==ZLIB_FILEFUNC_MODE_READ)
        iodevice->open(QIODevice::ReadOnly);
    else
    if (mode & ZLIB_FILEFUNC_MODE_EXISTING)
        iodevice->open(QIODevice::ReadWrite);
    else
    if (mode & ZLIB_FILEFUNC_MODE_CREATE)
        iodevice->open(QIODevice::WriteOnly);

    if (iodevice->isOpen()) {
        if (iodevice->isSequential()) {
            iodevice->close();
            return NULL;
        } else {
            return iodevice;
        }
    } else
        return NULL;
}
示例#2
0
void GameState::Serialize(QIODevice& f) {
    QString serialization;
    QXmlStreamWriter stream(&serialization);
    stream.setAutoFormatting(true);
    stream.writeStartDocument();
    stream.writeStartElement("SaveGame");

    stream.writeStartElement("Board");
    stream.writeAttribute("Width", QString::number(this->width));
    stream.writeAttribute("Height", QString::number(this->height));
    stream.writeAttribute("StepsPerformed", QString::number((this->stepNum)));
    for (uint i = 0; i < height; i++)
    {
        stream.writeCharacters("\n        ");
        for (uint j = 0; j < width; j++)
        {
            stream.writeCharacters(QString::number(this->board[i][j]) + " ");
        }
    }
    stream.writeCharacters("\n    ");
    stream.writeEndElement();

    stream.writeEndElement();
    stream.writeEndDocument();
    f.open(QIODevice::WriteOnly);
    f.write(serialization.toUtf8());
    f.close();
}
示例#3
0
bool KoStorePrivate::extractFile(const QString &srcName, QIODevice &buffer)
{
    if (!q->open(srcName))
        return false;

    if (!buffer.open(QIODevice::WriteOnly)) {
        q->close();
        return false;
    }
    // ### This could use KArchive::copy or something, no?

    QByteArray data;
    data.resize(8 * 1024);
    uint total = 0;
    for (int block = 0; (block = q->read(data.data(), data.size())) > 0; total += block) {
        buffer.write(data.data(), block);
    }

    if (q->size() != static_cast<qint64>(-1))
        Q_ASSERT(total == q->size());

    buffer.close();
    q->close();

    return true;
}
bool QIODeviceProto::open(QIODevice::OpenMode mode)
{
  QIODevice *item = qscriptvalue_cast<QIODevice*>(thisObject());
  if (item)
    return item->open(mode);
  return false;
}
MServiceMapperPrivate::ServiceInfo MServiceMapperPrivate::serviceInterfacePair(const QString &fileName) const
{
    MServiceMapperPrivate::ServiceInfo serviceInterfacePair;

    if ( m_serviceFileInfo.contains( fileName ) ) {
        serviceInterfacePair = m_serviceFileInfo.value( fileName );
    } else {
        QString absoluteFileName = QDir(m_serviceFileDir).absoluteFilePath(fileName);

        if (fileExistsAndReadable(absoluteFileName)) {
            QIODevice *file = accessFile(absoluteFileName);
            if (file->open(QIODevice::ReadOnly)) {
                QTextStream in(file);

                while (!in.atEnd()) {
                    QString line = in.readLine();

                    QStringList fields = line.split('=');

                    if (fields[0] == "Name") {
                        serviceInterfacePair.service=fields[1];
                    } else
                        if (fields[0] == "Interface") {
                            serviceInterfacePair.interface=fields[1];
                        }
                }
            }

            delete file;
        }
    }

    return serviceInterfacePair;
}
示例#6
0
文件: dtkLogger.cpp 项目: papadop/dtk
/*!
    \internal
    Reads the configuration out from a io device.
*/
void dtkLoggingPrivate::readSettings(QIODevice &device)
{
    QMutexLocker locker(&_mutexRegisteredCategory);
    {
        _logConfigItemList.clear();

        if (device.open(QIODevice::ReadOnly)) {
            QByteArray truearray("true");
            QByteArray line;
            while (!device.atEnd()) {
                line = device.readLine().replace(" ", "");
                line = line.simplified();
                const QList<QByteArray> pair = line.split('=');
                if (pair.count() == 2)
                    _logConfigItemList.append(dtkLogConfigFilterItem(QString::fromLatin1(pair.at(0))
                                                     , (pair.at(1).toLower() == truearray)));
            }
        }

        foreach (dtkLoggingCategory *category, _registeredCategories) {
            updateCategory(category);
        }

        _registerCategories = true;
    }
QMap<QString, StelLocation> StelLocationMgr::loadCitiesBin(const QString& fileName) const
{
	QMap<QString, StelLocation> res;
	QString cityDataPath;
	try
	{
		cityDataPath = StelFileMgr::findFile(fileName);
	}
	catch (std::runtime_error& e)
	{
		return res;
	}

	QFile sourcefile(cityDataPath);
	if (!sourcefile.open(QIODevice::ReadOnly))
	{
		qWarning() << "ERROR: Could not open location data file: " << cityDataPath;
		return res;
	}

	if (fileName.endsWith(".gz"))
	{
		QIODevice* d = KFilterDev::device(&sourcefile, "application/x-gzip", false);
		d->open(QIODevice::ReadOnly);
		QDataStream in(d);
		in.setVersion(QDataStream::Qt_4_6);
		in >> res;
		d->close();
		delete d;
		return res;
	}
示例#8
0
bool CharArchive::openAnimBoneCount()
{
    if (!isOpen()) {
        qWarning() << "CharArchive::openAnimBoneCount" << "archive not opened";
        return false;
    }

    _animBoneCount.clear();

    LgpIterator it = _io.iterator();
    while(it.hasNext()) {
        it.next();
        const QString &fileName = it.fileName();
        if(fileName.endsWith(".a", Qt::CaseInsensitive)) {
            QCoreApplication::processEvents();
            QIODevice *aFile = it.file();
            if(aFile && aFile->open(QIODevice::ReadOnly)) {
                quint32 boneCount;
                if(!aFile->seek(8) ||
                        aFile->read((char *)&boneCount, 4) != 4) {
                    qWarning() << "CharArchive::openAnimBoneCount" << "animation error" << fileName;
                    continue;
                }
                _animBoneCount.insert(boneCount, fileName.left(fileName.size()-2).toUpper());
            } else {
                return false;
            }
        }
    }

    return true;
}
示例#9
0
bool KTNEFWriter::writeFile( QIODevice &file ) {
  if ( !file.open( IO_WriteOnly ) )
    return false;

  QDataStream stream( &file );
  return writeFile( stream );
}
示例#10
0
/**
 * This tests the decompression using kfilterdev, basically.
 * To debug KTarPrivate::fillTempFile().
 *
 * @dataProvider setupData
 */
void KArchiveTest::testUncompress()
{
    QFETCH(QString, fileName);
    QFETCH(QString, mimeType);

    // testCreateTar must have been run first.
    QVERIFY(QFile::exists(fileName));
    QIODevice *filterDev = KFilterDev::deviceForFile(fileName, mimeType, true);
    QVERIFY(filterDev);
    QByteArray buffer;
    buffer.resize(8*1024);
    kDebug() << "buffer.size()=" << buffer.size();
    QVERIFY(filterDev->open(QIODevice::ReadOnly));

    qint64 totalSize = 0;
    qint64 len = -1;
    while (!filterDev->atEnd() && len != 0) {
        len = filterDev->read(buffer.data(), buffer.size());
        QVERIFY(len >= 0);
        totalSize += len;
        // kDebug() << "read len=" << len << " totalSize=" << totalSize;
    }
    filterDev->close();
    delete filterDev;
    // kDebug() << "totalSize=" << totalSize;
    QVERIFY(totalSize > 26000); // 27648 here when using gunzip
}
示例#11
0
const QByteArray& QxtMailAttachment::rawData() const
{
    if (qxt_d->content == 0)
    {
        qWarning("QxtMailAttachment::rawData(): Content not set!");
        static QByteArray defaultRv;
        return defaultRv;
    }
    if (qobject_cast<QBuffer *>(qxt_d->content.data()) == 0)
    {
        // content isn't hold in a buffer but in another kind of QIODevice
        // (probably a QFile...). Read the data and cache it into a buffer
        static QByteArray empty;
        QIODevice* c = content();
        if (!c->isOpen() && !c->open(QIODevice::ReadOnly))
        {
            qWarning() << "QxtMailAttachment::rawData(): Cannot open content for reading";
            return empty;
        }
        QBuffer* cache = new QBuffer();
        cache->open(QIODevice::WriteOnly);
        char buf[1024];
        while (!c->atEnd())
        {
            cache->write(buf, c->read(buf, 1024));
        }
        if (qxt_d->deleteContent && qxt_d->content)
        qxt_d->content->deleteLater();
        qxt_d->content = cache;
        qxt_d->deleteContent = true;
    }
    return qobject_cast<QBuffer *>(qxt_d->content.data())->data();
}
示例#12
0
void BenchmarkCodeCompletion::initTestCase()
{
    AutoTestShell::init();
    TestCore* core = new TestCore();
    core->initialize(KDevelop::Core::NoUi);

    DUChain::self()->disablePersistentStorage();

    // make sure we have a valid duchain for the global file
    DUChainReadLocker lock(DUChain::lock());
    if ( !DUChain::self()->chainForDocument(internalFunctionFile()) ) {
        kDebug() << "no internal function file found in DUChain, loading it manually";
        QString fileName = internalFunctionFile().str();
        QString mimeType = KMimeType::findByPath(fileName, 0, false)->name ();
        QIODevice* file = KFilterDev::deviceForFile (fileName, mimeType, false);
        if ( !file->open(QIODevice::ReadOnly) ) {
            kDebug() << "Could not open file" << fileName;
            return;
        }
        lock.unlock();
        parseAdditionalFile(internalFunctionFile(), file->readAll());
        delete file;
        DUChain::self()->storeToDisk();
    }
}
示例#13
0
void test_block(const QString &fileName)
{
    QIODevice *dev = KFilterDev::deviceForFile(fileName);
    if(!dev)
    {
        kdWarning() << "dev=0" << endl;
        return;
    }
    if(!dev->open(IO_ReadOnly))
    {
        kdWarning() << "open failed " << endl;
        return;
    }

    // This is what KGzipDev::readAll could do, if QIODevice::readAll was virtual....

    QByteArray array(1024);
    int n;
    while((n = dev->readBlock(array.data(), array.size())))
    {
        kdDebug() << "readBlock returned " << n << endl << endl;
        // QCString s(array,n+1); // Terminate with 0 before printing
        // printf("%s", s.data());

        kdDebug() << "dev.at = " << dev->at() << endl;
        // kdDebug() << "f.at = " << f.at() << endl;
    }
    dev->close();
    delete dev;
}
Replayer::Replayer(QObject *parent, const QString &filename)
    : QThread(parent), m_commandSeriesCounter(1),
    filename(filename), speed(1.0), playing(true)
{
    QIODevice *device = NULL;
    if (filename.endsWith(".png")) {
        QByteArray *data = new QByteArray(PNG2TXT(filename));
        device = new QBuffer(data);
    } else if (filename.endsWith(".qsgs")) {
        QFile *file = new QFile(filename);
        if (file->open(QFile::ReadOnly)) {
            char header;
            file->getChar(&header);
            if (header == '\0') {
                QByteArray content = file->readAll();
                delete file;

                QByteArray *data = new QByteArray(qUncompress(content));
                device = new QBuffer(data);
            } else {
                file->close();
                device = file;
            }
        } else {
            return;
        }
    }

    if (device == NULL)
        return;

    if (!device->open(QIODevice::ReadOnly | QIODevice::Text))
        return;

    while (!device->atEnd()) {
        QByteArray line = device->readLine();
        int split = line.indexOf(' ');

        Pair pair;
        pair.elapsed = line.left(split).toInt();
        pair.cmd = line.mid(split + 1);

        pairs << pair;
    }

    delete device;

    int time_offset = 0;
    pair_offset = 0;
    foreach (const Pair &pair, pairs) {
        Packet packet;
        if (packet.parse(pair.cmd)) {
            if (packet.getCommandType() == S_COMMAND_START_IN_X_SECONDS) {
                time_offset = pair.elapsed;
                break;
            }
        }
        pair_offset++;
    }
示例#15
0
/*!
    \internal
*/
bool QImageReaderPrivate::initHandler()
{
    // check some preconditions
    if (!device || (!deleteDevice && !device->isOpen() && !device->open(QIODevice::ReadOnly))) {
        imageReaderError = QImageReader::DeviceError;
        errorString = QLatin1String(QT_TRANSLATE_NOOP(QImageReader, "Invalid device"));
        return false;
    }

    // probe the file extension
    if (deleteDevice && !device->isOpen() && !device->open(QIODevice::ReadOnly) && autoDetectImageFormat) {
        QList<QByteArray> extensions = QImageReader::supportedImageFormats();
        if (!format.isEmpty()) {
            // Try the most probable extension first
            int currentFormatIndex = extensions.indexOf(format.toLower());
            if (currentFormatIndex > 0)
                extensions.swap(0, currentFormatIndex);
        }

        int currentExtension = 0;

        QFile *file = static_cast<QFile *>(device);
        QString fileName = file->fileName();

        do {
            file->setFileName(fileName + QLatin1Char('.')
                    + QString::fromLatin1(extensions.at(currentExtension++).constData()));
            file->open(QIODevice::ReadOnly);
        } while (!file->isOpen() && currentExtension < extensions.size());

        if (!device->isOpen()) {
            imageReaderError = QImageReader::FileNotFoundError;
            errorString = QLatin1String(QT_TRANSLATE_NOOP(QImageReader, "File not found"));
            file->setFileName(fileName); // restore the old file name
            return false;
        }
    }

    // assign a handler
    if (!handler && (handler = createReadHandlerHelper(device, format, autoDetectImageFormat, ignoresFormatAndExtension)) == 0) {
        imageReaderError = QImageReader::UnsupportedFormatError;
        errorString = QLatin1String(QT_TRANSLATE_NOOP(QImageReader, "Unsupported image format"));
        return false;
    }
    return true;
}
示例#16
0
bool KTNEFWriter::writeFile( QIODevice &file ) const
{
  if ( !file.open( QIODevice::WriteOnly ) ) {
    return false;
  }

  QDataStream stream( &file );
  return writeFile( stream );
}
bool LibSingleFileInterface::copyFiles(const QList<QVariant> & files, const QString & destinationDirectory, Kerfuffle::ExtractionOptions options)
{
    Q_UNUSED(files)
    Q_UNUSED(options)

    QString outputFileName = destinationDirectory;
    if (!destinationDirectory.endsWith(QLatin1Char('/'))) {
        outputFileName += QLatin1Char('/');
    }
    outputFileName += uncompressedFileName();

    outputFileName = overwriteFileName(outputFileName);
    if (outputFileName.isEmpty()) {
        return true;
    }

    kDebug() << "Extracting to" << outputFileName;

    QFile outputFile(outputFileName);
    if (!outputFile.open(QIODevice::WriteOnly)) {
        kDebug() << "Failed to open output file" << outputFile.errorString();
        emit error(i18nc("@info", "Ark could not extract <filename>%1</filename>.", outputFile.fileName()));

        return false;
    }

    QIODevice *device = KFilterDev::deviceForFile(filename(), m_mimeType, false);
    if (!device) {
        kDebug() << "Could not create KFilterDev";
        emit error(i18nc("@info", "Ark could not open <filename>%1</filename> for extraction.", filename()));

        return false;
    }

    device->open(QIODevice::ReadOnly);

    qint64 bytesRead;
    QByteArray dataChunk(1024*16, '\0');   // 16Kb

    while (true) {
        bytesRead = device->read(dataChunk.data(), dataChunk.size());

        if (bytesRead == -1) {
            emit error(i18nc("@info", "There was an error while reading <filename>%1</filename> during extraction.", filename()));
            break;
        } else if (bytesRead == 0) {
            break;
        }

        outputFile.write(dataChunk.data(), bytesRead);
    }

    delete device;

    return true;
}
示例#18
0
Replayer::Replayer(QObject *parent, const QString &filename)
	:QThread(parent), m_isOldVersion(false), m_commandSeriesCounter(1),
	  filename(filename), speed(1.0), playing(true)
{
	QIODevice *device = NULL;
	if(filename.endsWith(".png")){
		QByteArray *data = new QByteArray(PNG2TXT(filename));
		QBuffer *buffer = new QBuffer(data);
		device = buffer;
	}else if(filename.endsWith(".txt")){
		QFile *file = new QFile(filename);
		device = file;
	}

	if(device == NULL)
		return;

	if(!device->open(QIODevice::ReadOnly | QIODevice::Text))
		return;

	typedef char buffer_t[1024];

	initCommandPair();
	while(!device->atEnd()){
		buffer_t line;
		memset(line, 0, sizeof(buffer_t));
		device->readLine(line, sizeof(buffer_t));

		char *space = strchr(line, ' ');
		if(space == NULL)
			continue;

		*space = '\0';
		QString cmd = space + 1;
		int elapsed = atoi(line);

		//@todo: There is a serious problem that the old protocol didn't has
		//any tag or type definition for the sent messages, and if the old protocol
		// wants to be translated to the new protocol, there is no information for the package type
		//and client will be confused of showing dialog or not.
		commandTranslation(cmd);

		Pair pair;
		pair.elapsed = elapsed;
		pair.cmd = cmd;

		pairs << pair;
	}

	if(m_isOldVersion){
		QMessageBox::warning(NULL, tr("Warning"), tr("The replay use old protocol"));
	}

	delete device;
}
示例#19
0
/*!
 * Returns the data, modified by setData if modified, for the file named \a filePath.
 * \sa file(), fileData(), modifiedFile()
 */
QByteArray Archive::modifiedFileData(const QString &filePath)
{
	QIODevice *io = modifiedFile(filePath);
	if(io == NULL || !io->open(QIODevice::ReadOnly)) {
		qWarning() << "Archive::modifiedFileData error";
		return QByteArray();
	}
	QByteArray data = io->readAll();
	io->close();
	return data;
}
示例#20
0
void
JamendoXmlParser::readConfigFile( const QString &filename )
{
    if( m_aborted )
        return;
 
    m_nNumberOfTracks = 0;
    m_nNumberOfAlbums = 0;
    m_nNumberOfArtists = 0;

    if( !QFile::exists( filename ) )
    {
        debug() << "jamendo xml file does not exist";
        return;
    }

    QIODevice *file = KFilterDev::deviceForFile( filename, "application/x-gzip", true );

    if( !file || !file->open( QIODevice::ReadOnly ) )
    {
        debug() << "JamendoXmlParser::readConfigFile error reading file";
        return;
    }

    m_reader.setDevice( file );

    m_dbHandler->destroyDatabase();
    m_dbHandler->createDatabase();

    m_dbHandler->begin(); //start transaction (MAJOR speedup!!)
    while( !m_reader.atEnd() )
    {
        m_reader.readNext();
        if( m_reader.isStartElement() )
        {
            QStringRef localname = m_reader.name();
            if( localname == "artist" )
            {
                readArtist();
            }
        }
    }


    m_dbHandler->commit(); //complete transaction
    //as genres are just user tags, remove any that are not applied to at least 10 albums to weed out the worst crap
    //perhaps make this a config option
    m_dbHandler->trimGenres( 10 );

    file->close();
    delete file;
    QFile::remove( filename );
}
示例#21
0
文件: qioapi.cpp 项目: 0----0/ckb
voidpf ZCALLBACK qiodevice_open_file_func (
   voidpf opaque,
   voidpf file,
   int mode)
{
    QIODevice_descriptor *d = reinterpret_cast<QIODevice_descriptor*>(opaque);
    QIODevice *iodevice = reinterpret_cast<QIODevice*>(file);
    QIODevice::OpenMode desiredMode;
    if ((mode & ZLIB_FILEFUNC_MODE_READWRITEFILTER)==ZLIB_FILEFUNC_MODE_READ)
        desiredMode = QIODevice::ReadOnly;
    else if (mode & ZLIB_FILEFUNC_MODE_EXISTING)
        desiredMode = QIODevice::ReadWrite;
    else if (mode & ZLIB_FILEFUNC_MODE_CREATE)
        desiredMode = QIODevice::WriteOnly;
    if (iodevice->isOpen()) {
        if ((iodevice->openMode() & desiredMode) == desiredMode) {
            if (desiredMode != QIODevice::WriteOnly
                    && iodevice->isSequential()) {
                // We can use sequential devices only for writing.
                delete d;
                return NULL;
            } else {
                if ((desiredMode & QIODevice::WriteOnly) != 0) {
                    // open for writing, need to seek existing device
                    if (!iodevice->isSequential()) {
                        iodevice->seek(0);
                    } else {
                        d->pos = iodevice->pos();
                    }
                }
            }
            return iodevice;
        } else {
            delete d;
            return NULL;
        }
    }
    iodevice->open(desiredMode);
    if (iodevice->isOpen()) {
        if (desiredMode != QIODevice::WriteOnly && iodevice->isSequential()) {
            // We can use sequential devices only for writing.
            iodevice->close();
            delete d;
            return NULL;
        } else {
            return iodevice;
        }
    } else {
        delete d;
        return NULL;
    }
}
示例#22
0
/*!
    returns the number of columns in the file \c fileName.
*/
int AsciiFilter::columnNumber(const QString & fileName){
	QString line;
	QStringList lineStringList;

	QIODevice *device = KFilterDev::deviceForFile(fileName);
	if (!device->open(QIODevice::ReadOnly))
		return 0;

	QTextStream in(device);
	line = in.readLine();
	lineStringList = line.split( QRegExp("\\s+")); //TODO
	return lineStringList.size();
}
示例#23
0
文件: manifest.cpp 项目: KDE/okular
QByteArray Manifest::decryptFile( const QString &filename, const QByteArray &fileData )
{
#ifdef QCA2
  ManifestEntry *entry = entryByName( filename );

  if ( ! QCA::isSupported( "sha1" ) ) {
    KMessageBox::error( 0, i18n("This document is encrypted, and crypto support is compiled in, but a hashing plugin could not be located") );
    // in the hope that it wasn't really encrypted...
    return QByteArray( fileData );
  }

  if ( ! QCA::isSupported( "pbkdf2(sha1)") )  {
    KMessageBox::error( 0, i18n("This document is encrypted, and crypto support is compiled in, but a key derivation plugin could not be located") );
    // in the hope that it wasn't really encrypted...
    return QByteArray( fileData );
  }

  if ( ! QCA::isSupported( "blowfish-cfb") )  {
    KMessageBox::error( 0, i18n("This document is encrypted, and crypto support is compiled in, but a cipher plugin could not be located") );
    // in the hope that it wasn't really encrypted...
    return QByteArray( fileData );
  }

  QByteArray decryptedData;
  checkPassword( entry, fileData, &decryptedData );

  if (! m_haveGoodPassword ) {
    return QByteArray();
  }

  QIODevice *decompresserDevice = new KCompressionDevice( new QBuffer( &decryptedData, 0 ), true, KCompressionDevice::GZip);
  if( !decompresserDevice ) {
    qCDebug(OkularOooDebug) << "Couldn't create decompressor";
    // hopefully it isn't compressed then!
    return QByteArray( fileData );
  }

  static_cast<KFilterDev*>( decompresserDevice )->setSkipHeaders( );

  decompresserDevice->open( QIODevice::ReadOnly );

  return decompresserDevice->readAll();

#else
  // TODO: This should have a proper parent
  KMessageBox::error( 0, i18n("This document is encrypted, but Okular was compiled without crypto support. This document will probably not open.") );
  // this is equivalent to what happened before all this Manifest stuff :-)
  return QByteArray( fileData );
#endif
}
示例#24
0
bool Record::open()
{
    QIODevice *device = new QFile(m_fileName);
    if (!device->open(QFile::ReadOnly))
        return false;

    char header;
    device->getChar(&header);
    if (header == '\0') {
        m_format = CompressedText;
        QByteArray content = device->readAll();
        delete device;

        QByteArray *data = new QByteArray(qUncompress(content));
        device = new QBuffer(data);
        device->open(QFile::ReadOnly);
    } else {
        m_format = PlainText;
        device->ungetChar(header);
        device->seek(0);
    }

    m_commands.clear();
    while (!device->atEnd()) {
        QByteArray line = device->readLine();
        int split = line.indexOf(' ');

        Command command;
        command.elapsed = line.left(split).toInt();
        command.data = line.mid(split + 1);

        m_commands << command;
    }

    return true;
}
示例#25
0
/*!
  returns the number of lines in the file \c fileName.
*/
long AsciiFilter::lineNumber(const QString & fileName){
	//TODO: compare the speed of this function with the speed of wc from GNU-coreutils.
	QIODevice *device = KFilterDev::deviceForFile(fileName);
	if (!device->open(QIODevice::ReadOnly))
		return 0;

	QTextStream in(device);
	long rows=0;
	while (!in.atEnd()){
		in.readLine();
		rows++;
	}

	return rows;
}
示例#26
0
QString KSVGLoader::loadXML(::KURL url)
{
	QString tmpFile;
	if(KIO::NetAccess::download(url, tmpFile, 0))
	{
		QIODevice *dev = KFilterDev::deviceForFile(tmpFile, "application/x-gzip", true);
		QByteArray contents;
		if(dev->open(IO_ReadOnly))
			contents = dev->readAll();
		delete dev;
		KIO::NetAccess::removeTempFile(tmpFile);
		return QString(contents);
	}

	return QString::null;
}
示例#27
0
bool Chunks::write(QIODevice &iODevice, qint64 pos, qint64 count)
{
    if (count == -1)
        count = _size;
    bool ok = iODevice.open(QIODevice::WriteOnly);
    if (ok)
    {
        for (qint64 idx=pos; idx < count; idx += BUFFER_SIZE)
        {
            QByteArray ba = data(idx, BUFFER_SIZE);
            iODevice.write(ba);
        }
        iODevice.close();
    }
    return ok;
}
void
MagnatuneXmlParser::readConfigFile( const QString &filename )
{
    DEBUG_BLOCK
    m_nNumberOfTracks = 0;
    m_nNumberOfAlbums = 0;
    m_nNumberOfArtists = 0;

    QDomDocument doc( "config" );

    if ( !QFile::exists( filename ) )
    {
        debug() << "Magnatune xml file does not exist";
        return;
    }

    QIODevice *file = KFilterDev::deviceForFile( filename, "application/x-bzip2", true );
    if ( !file || !file->open( QIODevice::ReadOnly ) ) {
        debug() << "MagnatuneXmlParser::readConfigFile error reading file";
        return ;
    }
    if ( !doc.setContent( file ) )
    {
        debug() << "MagnatuneXmlParser::readConfigFile error parsing file";
        file->close();
        return ;
    }
    file->close();
    delete file;


    m_dbHandler->destroyDatabase();
    m_dbHandler->createDatabase();

    //run through all the elements
    QDomElement docElem = doc.documentElement();


    m_dbHandler->begin(); //start transaction (MAJOR speedup!!)
    parseElement( docElem );
    m_dbHandler->commit(); //complete transaction

    delete m_pCurrentArtist;
    delete m_pCurrentAlbum;

    return ;
}
示例#29
0
QNetworkRequest QNetworkAccessManagerPrivate::prepareMultipart(const QNetworkRequest &request, QHttpMultiPart *multiPart)
{
    // copy the request, we probably need to add some headers
    QNetworkRequest newRequest(request);

    // add Content-Type header if not there already
    if (!request.header(QNetworkRequest::ContentTypeHeader).isValid()) {
        QByteArray contentType;
        contentType.reserve(34 + multiPart->d_func()->boundary.count());
        contentType += "multipart/";
        switch (multiPart->d_func()->contentType) {
        case QHttpMultiPart::RelatedType:
            contentType += "related";
            break;
        case QHttpMultiPart::FormDataType:
            contentType += "form-data";
            break;
        case QHttpMultiPart::AlternativeType:
            contentType += "alternative";
            break;
        default:
            contentType += "mixed";
            break;
        }
        // putting the boundary into quotes, recommended in RFC 2046 section 5.1.1
        contentType += "; boundary=\"" + multiPart->d_func()->boundary + "\"";
        newRequest.setHeader(QNetworkRequest::ContentTypeHeader, QVariant(contentType));
    }

    // add MIME-Version header if not there already (we must include the header
    // if the message conforms to RFC 2045, see section 4 of that RFC)
    QByteArray mimeHeader("MIME-Version");
    if (!request.hasRawHeader(mimeHeader))
        newRequest.setRawHeader(mimeHeader, QByteArray("1.0"));

    QIODevice *device = multiPart->d_func()->device;
    if (!device->isReadable()) {
        if (!device->isOpen()) {
            if (!device->open(QIODevice::ReadOnly))
                qWarning("could not open device for reading");
        } else {
            qWarning("device is not readable");
        }
    }

    return newRequest;
}
示例#30
0
DrMain *PPDLoader::readFromFile(const QString &filename)
{
    // Initialization
    m_groups.clear();
    m_option = NULL;
    m_fonts.clear();
    // Open driver file
    QIODevice *d = KFilterDev::deviceForFile(filename);
    if(d && d->open(IO_ReadOnly))
    {
        DrMain *driver = new DrMain;
        bool result = true;

        m_groups.push(driver);
        kdeprint_ppdscanner_init(d);
        if(kdeprint_ppdparse(this) != 0)
            result = false;
        kdeprint_ppdscanner_terminate(true);

        if(result)
        {
            if(m_groups.size() > 1)
                kdWarning(500) << "PPD syntax error, GROUP specification not correctly closed" << endl;
            if(driver->has("foodata"))
            {
                Foomatic2Loader loader;
                if(loader.readFromBuffer(driver->get("foodata")))
                {
                    driver = loader.modifyDriver(driver);
                }
                else
                    kdWarning(500) << "PPD syntax error, Foomatic data read failed" << endl;
            }
            processPageSizes(driver);
            if(!m_fonts.isEmpty())
                driver->set("fonts", m_fonts.join(","));
            return driver;
        }
        else
            kdWarning(500) << "PPD syntax error, PPD parse failed" << endl;
        delete driver;
        m_ps.clear();
    }
    else
        kdWarning(500) << "PPD read error, unable to open device for file " << filename << endl;
    return 0;
}