/** * @brief Flushes output stream and closes stream if requested. * @param Whether to close the current stream. Defaults to true. */ void Logger::closeLogger(bool closeStream) { if (outputStream) { outputStream->flush(); if (closeStream && outputStream->device() != 0) { QIODevice *device = outputStream->device(); if (device->isOpen()) { device->close(); } } } if (errorStream) { errorStream->flush(); if (closeStream && errorStream->device() != 0) { QIODevice *device = errorStream->device(); if (device->isOpen()) { device->close(); } } } instance->pendingTimer.stop(); instance = 0; }
void Worker::peerReadyReadHandler(void) { QIODevice* peer = qobject_cast<QIODevice*>(this->sender()); Q_ASSERT(peer != 0); if (this->m_state == Worker::ErrorState) { // Peer has not disconnected (though it should have) - closing the connection Q_EMIT this->error(Worker::UnknownError); peer->close(); return; } QByteArray buf; buf = peer->readAll(); this->m_buf.append(buf); bool cont; do { cont = false; switch(this->m_state) { case Worker::ConnectedState: cont = this->readGreeting(); break; case Worker::GreetingReceivedState: this->parseGreeting(); break; case Worker::AwaitingAuthenticationState: this->authenticate(); break; case Worker::AwaitingRequestState: this->parseRequest(); break; case Worker::RequestReceivedState: this->m_state = Worker::FatalErrorState; break; case Worker::ConnectionProxiedState: Q_ASSERT(this->m_target != 0); this->m_target->write(this->m_buf); this->m_target->flush(); this->m_buf.clear(); break; case Worker::ErrorState: case Worker::FatalErrorState: Q_ASSERT(false); break; } } while (cont); if (this->m_state == Worker::FatalErrorState) { peer->close(); } }
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; }
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; }
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(); }
/** * 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 }
QPixmap CustomizationService::getServerLogo(const Account& account) { QPixmap logo = QPixmap(":/images/seafile-24.png"); if (account.serverInfo.customLogo.isEmpty()) { return logo; } QUrl url = account.getAbsoluteUrl(account.serverInfo.customLogo); QIODevice* buf = disk_cache_->data(url); if (buf) { logo.loadFromData(buf->readAll()); buf->close(); delete buf; } if (!reqs_.contains(url.toString())) { FetchCustomLogoRequest* req = new FetchCustomLogoRequest(url); connect(req, SIGNAL(success(const QUrl&)), this, SLOT(onServerLogoFetched(const QUrl&))); connect(req, SIGNAL(failed(const ApiError&)), this, SLOT(onServerLogoFetchFailed(const ApiError&))); req->send(); reqs_[url.toString()] = req; }
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; }
/*! Writes the contents of \a document to the text document \a content. It is left up to the calling code to \l {QContent::commit()}{commit} the changes in \a content to the document system. Returns true if the write was successful and false otherwise. */ bool NotesDemo::writeContent( QTextDocument *document, QContent *content ) { // Attempt to open the content in write-only mode. If the open succeeds QContent // will construct a new I/O device and return a pointer to it, the caller takes // ownership of the I/O device and is responsible for deleting it. QIODevice *ioDevice = content->open( QIODevice::WriteOnly ); if ( !ioDevice ) { qWarning() << "Could not open the new content object to write to!!"; return false; } // Gets the plain text content of the text document and converts it to an 8-bit // ASCII byte array before writing it to the I/O device. // (This assumes that the notes are short enough to fit into memory. For longer // documents, use QTextDocument::begin(), QTextDocument::end() and QTextDocument::findBlock(int).) int bytesWritten = ioDevice->write( document->toPlainText().toAscii() ); // Close the I/O device and delete it. ioDevice->close(); delete ioDevice; if ( bytesWritten < 0 ) { qWarning() << "Error while trying to create a new notes object!!"; return false; } else { return true; } }
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; }
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 ; }
void KHTMLPageCacheEntry::endData() { m_complete = true; m_file->write(m_buffer); m_buffer.clear(); m_file->close(); }
void NetworkDump::Close() { Instance().dumpStream << QDateTime::currentDateTime().toString("dd/MM/yyyy hh:mm:ss") << " -- OpenJabNab End --" << endl; QIODevice * d = Instance().dumpStream.device(); if (d) { d->close(); delete d; } }
/*! * 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; }
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 ); }
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; } }
/*! Read the unformatted contents of the file associated with a QContent into \a data. If \a data is not empty the contents will be overridden. Returns true if data could be read from the file and false otherwise. */ bool QContent::load(QByteArray &data) const { QIODevice *dev = open(); if (!dev) return false; if (dev->size() > 0) data = dev->readAll(); dev->close(); delete dev; return true; }
void QMQTT::SslNetwork::onSocketReadReady() { QIODevice *ioDevice = _socket->ioDevice(); while(!ioDevice->atEnd()) { if(_bytesRemaining == 0) { if (!ioDevice->getChar(reinterpret_cast<char *>(&_header))) { // malformed packet emit error(QAbstractSocket::OperationError); ioDevice->close(); return; } _bytesRemaining = readRemainingLength(); if (_bytesRemaining < 0) { // malformed remaining length emit error(QAbstractSocket::OperationError); ioDevice->close(); return; } } QByteArray data = ioDevice->read(_bytesRemaining); _buffer.append(data); _bytesRemaining -= data.size(); if(_bytesRemaining == 0) { Frame frame(_header, _buffer); _buffer.clear(); emit received(frame); } } }
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; }
bool saveToCache( const QString &contents, const QString &filename ) { QIODevice *fd = ::getBZip2device(filename); if ( !fd ) return false; if (!fd->open(QIODevice::WriteOnly)) { delete fd; return false; } fd->write( contents.toUtf8() ); fd->close(); delete fd; return true; }
int ZCALLBACK qiodevice_close_file_func ( voidpf /*opaque UNUSED*/, voidpf stream) { QIODevice *device = reinterpret_cast<QIODevice*>(stream); #ifdef QUAZIP_QSAVEFILE_BUG_WORKAROUND // QSaveFile terribly breaks the is-a idiom: // it IS a QIODevice, but it is NOT compatible with it: close() is private QSaveFile *file = qobject_cast<QSaveFile*>(device); if (file != NULL) { // We have to call the ugly commit() instead: return file->commit() ? 0 : -1; } #endif device->close(); return 0; }
void test_textstream(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; } QTextStream ts(dev); printf("%s\n", ts.read().latin1()); dev->close(); delete dev; }
void test_getch(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; } int ch; while((ch = dev->getch()) != -1) printf("%c", ch); dev->close(); delete dev; }
/*! Saves \a data to the file associated with a QContent. If the QContent is associated with an existing file its contents will be overwritten, otherwise a new file will be created. In order to create a new file the QContent must have valid values of name() and type(). Returns true if all the data is written to the file and false otherwise. \bold {Saving data to a new file:} \code bool saveData( const QString &name, const QString &type, const QByteArray &data ) { QContent content; content.setName( name ); content.setType( type ); if( content.save( data ) ) { content.commit(); return true; } else { return false; } } \endcode */ bool QContent::save(const QByteArray &data) { Q_ASSERT( d.constData() != NULL ); if( d.constData() == NULL ) return false; QIODevice *dev = open(QIODevice::WriteOnly); if (!dev) return false; int bytesWritten = dev->write(data); dev->close(); delete dev; if (bytesWritten != data.size()) { return false; } return true; }
void QWebdav::replyFinished(QNetworkReply* reply) { #ifdef DEBUG_WEBDAV qDebug() << "QWebdav::replyFinished()"; #endif disconnect(reply, SIGNAL(readyRead()), this, SLOT(replyReadyRead())); disconnect(reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(replyError(QNetworkReply::NetworkError))); QIODevice* dataIO = m_inDataDevices.value(reply, 0); if (dataIO != 0) { dataIO->write(reply->readAll()); static_cast<QFile*>(dataIO)->flush(); dataIO->close(); delete dataIO; } m_inDataDevices.remove(reply); QMetaObject::invokeMethod(this,"replyDeleteLater", Qt::QueuedConnection, Q_ARG(QNetworkReply*, reply)); }
/*! Reads the contents of the text document \a content into \a document. Returns true if the read was successful and false otherwise. */ bool NotesDemo::readContent( QTextDocument *document, QContent *content ) { // Attempt to open the content in read-only mode. If the open succeeds QContent // will construct a new I/O device and return a pointer to it, the caller takes // ownership of the I/O device and is responsible for deleting it. QIODevice *ioDevice = content->open( QIODevice::ReadOnly ); if ( !ioDevice ) { qWarning() << "Could not open the new content object to read from!!"; return false; } QByteArray bytes = ioDevice->readAll(); // Convert the string from an 8-bit ASCII byte array and set it as the plain text // content of the document. document->setPlainText( QString::fromAscii( bytes ) ); // Close the I/O device and destroy it. ioDevice->close(); delete ioDevice; return true; }
void GameState::Deserialize(QIODevice& f) { f.open(QIODevice::ReadOnly); QXmlStreamReader stream(&f); while (!stream.atEnd()) { stream.readNext(); if (stream.isStartElement()) { if (stream.name() == "Board") { this->height = stream.attributes().value("Height").toInt(); this->width = stream.attributes().value("Width").toInt(); this->stepNum = stream.attributes().value("StepsPerformed").toInt(); QStringList tmp = stream.readElementText().simplified().split(" "); board = std::move(vector<vector<short>>(height, vector<short>(width, 0))); for (uint i = 0; i < height; i++) for (uint j = 0; j < width; j++) this->board[i][j] = QString(tmp[i*height+j]).toShort(); } } } f.close(); }
void test_block_write(const QString &fileName) { QIODevice *dev = KFilterDev::deviceForFile(fileName); if(!dev) { kdWarning() << "dev=0" << endl; return; } if(!dev->open(IO_WriteOnly)) { kdWarning() << "open failed " << endl; return; } QCString s("hello\n"); int ret = dev->writeBlock(s, s.size() - 1); kdDebug() << "writeBlock ret=" << ret << endl; // ret = dev->writeBlock( s, s.size()-1 ); // kdDebug() << "writeBlock ret=" << ret << endl; dev->close(); delete dev; }
voidpf ZCALLBACK qiodevice_open_file_func ( voidpf /*opaque UNUSED*/, voidpf file, int mode) { 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 (iodevice->isSequential()) { return NULL; } else { if ((desiredMode & QIODevice::WriteOnly) != 0) { // open for writing, need to seek existing device iodevice->seek(0); } } return iodevice; } else { return NULL; } } iodevice->open(desiredMode); if (iodevice->isOpen()) { if (iodevice->isSequential()) { iodevice->close(); return NULL; } else { return iodevice; } } else return NULL; }
QImage ExifContentPlugin::thumbnail( const QContent &content, const QSize &size, Qt::AspectRatioMode mode ) { QImage image; QIODevice *device = content.open(); if (device) { QExifImageHeader exif; if (exif.loadFromJpeg(device)) { image = exif.thumbnail(); if (!image.isNull() && size.isValid()) image = image.scaled(size, mode, Qt::SmoothTransformation); } device->close(); delete device; } return image; }