当前位置: 首页>>代码示例>>C++>>正文


C++ QByteArray::left方法代码示例

本文整理汇总了C++中QByteArray::left方法的典型用法代码示例。如果您正苦于以下问题:C++ QByteArray::left方法的具体用法?C++ QByteArray::left怎么用?C++ QByteArray::left使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在QByteArray的用法示例。


在下文中一共展示了QByteArray::left方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。

示例1: writeToFile

void Updater::writeToFile()
{
    QNetworkReply *reply = ( QNetworkReply * )sender();
    QByteArray arr = reply->readAll();
    bool err = false;
    if ( firstChunk )
    {
#if defined Q_OS_WIN
        err = arr.left( 2 ) != "MZ";
#elif defined Q_OS_LINUX
        err = arr.left( 4 ) != "\x7F""ELF" && arr.left( 2 ) != "#!";
#endif
        firstChunk = false;
    }
    if ( err || updateFile.write( arr ) != arr.size() )
        reply->abort();
}
开发者ID:JERUKA9,项目名称:QMPlay2,代码行数:17,代码来源:Updater.cpp

示例2: SubmitQuery

void SocketHandler::SubmitQuery(int request_type, QString data)
{
    // Make a new tcp socket, and connect to the server
    socket = new QTcpSocket(this);
    socket->connectToHost(host, port);

    // Wait a few seconds for a connection
    if (socket->waitForConnected(5000))
    {
        // When connected, build a socket query based on parameters
        QString temp;
        qDebug() << "[SOCKET HANDLER] : Connected.";
        // Byte array for converting qstring to const char *
        QByteArray bytes;
        const char * query;

        switch(request_type)
        {
            case REQ_NEW_ITEM:
                qDebug() << "[SOCKET HANDLER] : Requesting new job.";
                temp = "n^" + data;
                break;
            case UPD_CUR_ITEM:
                qDebug() << "[SOCKET HANDLER] : Requesting update on job.";
                temp = "u^" + data;
                break;
            default:
                break;
        }

        // Convert data for sending
        bytes = temp.toLocal8Bit();
        query = bytes.data();

        // Send query
        socket->write(query);
        socket->waitForBytesWritten(10000);

        // Recieve a response from the server
        QByteArray arr;
        while(!arr.contains(SERVER_RECV_DELIMITER))
        {
            socket->waitForReadyRead();
            arr += socket->readAll();
        }

        int b = arr.indexOf(SERVER_RECV_DELIMITER);
        QByteArray message = arr.left(b);
        arr = arr.mid(b);
        qDebug() << "[SOCKET HANDLER] : DONE." ;
        emit dataReady(message);
        socket->close();
    }
    else
    {
        qDebug() << "[SOCKET HANDLER] : COULD NOT CONNECT.";
    }
}
开发者ID:joshbosley,项目名称:OPAS,代码行数:58,代码来源:sockethandler.cpp

示例3: buffer

QList<FormData> HTTPConnection::parseFormData() const {
    // make sure we have the correct MIME type
    QList<QByteArray> elements = _requestHeaders.value("Content-Type").split(';');

    QString contentType = elements.at(0).trimmed();

    if (contentType != "multipart/form-data") {
        return QList<FormData>();
    }

    // retrieve the boundary marker
    QByteArray boundary;
    for (int ii = 1, nn = elements.size(); ii < nn; ii++) {
        QByteArray element = elements.at(ii).trimmed();
        if (element.startsWith("boundary")) {
            boundary = element.mid(element.indexOf('=') + 1).trimmed();
            break;
        }
    }
    
    QByteArray start = "--" + boundary;
    QByteArray end = "\r\n--" + boundary + "--\r\n";

    QList<FormData> data;
    QBuffer buffer(const_cast<QByteArray*>(&_requestContent));
    buffer.open(QIODevice::ReadOnly);
    while (buffer.canReadLine()) {
        QByteArray line = buffer.readLine().trimmed();
        if (line == start) {
            FormData datum;
            while (buffer.canReadLine()) {
                QByteArray line = buffer.readLine().trimmed();
                if (line.isEmpty()) {
                    // content starts after this line
                    int idx = _requestContent.indexOf(end, buffer.pos());
                    if (idx == -1) {
                        qWarning() << "Missing end boundary." << _address;
                        return data;
                    }
                    datum.second = _requestContent.mid(buffer.pos(), idx - buffer.pos());
                    data.append(datum);
                    buffer.seek(idx + end.length());

                } else {
                    // it's a header element
                    int idx = line.indexOf(':');
                    if (idx == -1) {
                        qWarning() << "Invalid header line." << _address << line;
                        continue;
                    }
                    datum.first.insert(line.left(idx).trimmed(), line.mid(idx + 1).trimmed());
                }
            }
        }
    }

    return data;
}
开发者ID:howard-stearns,项目名称:hifi,代码行数:58,代码来源:HTTPConnection.cpp

示例4: data_parse

void encoder_tcpsocket::data_parse(QByteArray data)
{
    qDebug()<<data;
    int length = data.left(4).toInt(NULL,10);
    if(length <= 0)
        return;

    QByteArray code = data.mid(4,4); /**< 操作数 */
    qDebug()<<code;
    ///获取服务器时间
    if(code.operator ==(GET_DEVICE_TIME))
    {
        send_info_to_host(GET_DEVICE_TIME,
                          QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss"));
    }
    ///获取设备地址
    else if(code.operator ==(GET_DEVICE_ADDRESS))
    {
        send_info_to_host(GET_DEVICE_ADDRESS,
                          device_setting_read.settings_addr);
    }
    ///获取设备状态,一般为解码器
    else if(code.operator ==(GET_DEVICE_STATE))
    {
        send_info_to_host(GET_DEVICE_STATE,
                          QString::number(device_setting_read.settings_state).toLatin1());
    }
    ///获取心跳
    else if(code.operator ==(GET_DEVICE_HEART))
    {
        send_info_to_host(GET_DEVICE_HEART,
                          "0000");
    }
    ///设置设备时间
    else if(code.operator ==(SET_DEVICE_TIME))
    {
        QByteArray current_time = data.mid(8,19);
        char set_time[50];
        sprintf(set_time,"time -s \" %s \"\n",current_time.data());
        system(set_time);
    }
    ///设置设备重启
    else if(code.operator ==(SET_DEVICE_EXIT))
    {
        this->close();
        system("reboot\n");
    }
    ///设置解码器IP
    else if(code.operator ==(SET_DEVICE_DECODERIP))
    {
        emit change_decoder_ip(data.mid(8,length - 8));
    }
    ///设置停止实时显示
    else if(code.operator ==(SET_DEVICE_STOP))
    {
        emit change_decoder_ip("127.0.0.1");
    }
}
开发者ID:sdusky,项目名称:encoder_device,代码行数:58,代码来源:encoder_tcpsocket.cpp

示例5: main

	virtual void main()
	{
		//init
		bool v = getFlag("v");

		//load ids and lengths
		QHash<QByteArray, int> ids;
		QSharedPointer<QFile> file = Helper::openFileForReading(getInfile("ids"));
		while (!file->atEnd())
		{
			QByteArray line = file->readLine().trimmed();
			if (line.isEmpty() || line[0]=='#') continue;
			QList<QByteArray> parts = line.split('\t');
			int length = -1;
			if (parts.count()>1)
			{
				length = Helper::toInt(parts[1], "length value");
			}
			ids.insert(parts[0], length);
		}

		//open output stream
		FastqOutfileStream outfile(getOutfile("out"), false);

		//parse input and write output
		FastqFileStream stream(getInfile("in"));
		FastqEntry entry;
		while (!stream.atEnd())
		{
			stream.readEntry(entry);

			QByteArray id = entry.header.trimmed();
			id = id.mid(1);
			int comment_start = id.indexOf(' ');
			if (comment_start!=-1) id = id.left(comment_start);
			int length = ids.value(id, -2);
			if (length==-2) //id not in list
			{
				if (!v) continue;

				outfile.write(entry);
			}
			else if (length==-1) //id is in list, but no length given
			{
				if (v) continue;

				outfile.write(entry);
			}
			else if (length>=1) //id is in list and length given
			{
				if (v) continue;

				entry.bases.resize(length);
				entry.qualities.resize(length);
				outfile.write(entry);
			}
		}
	}
开发者ID:imgag,项目名称:ngs-bits,代码行数:58,代码来源:main.cpp

示例6: decrypt

QString jsBridge::decrypt(QString data, QString hint)
{
    bool error = false;
    while (true) {
        PasswordDialog pwd(qApp->activeWindow(), false);
        pwd.setHint(hint);
        pwd.setError(error);
        if (pwd.exec() == QDialog::Accepted){

            RC2_KEY key;
            QByteArray b = QByteArray::fromBase64(data.toLatin1());

            QByteArray r = QCryptographicHash::hash(pwd.getPassword().toUtf8(), QCryptographicHash::Md5);
            RC2_set_key(&key, r.size(), (const unsigned char*)r.data(), 64);

            unsigned char * buf2 = new unsigned char[8];

            QByteArray result;

            while (b.size()>0) {
                QByteArray x = b.left(8);
                RC2_ecb_encrypt((const unsigned char*)x.data(),buf2,&key,RC2_DECRYPT);
                result += QByteArray((const char *)buf2, x.size());
                b.remove(0, 8);
            }

            QString crc1 = QString::fromUtf8(result.left(4));
            result.remove(0, 4);

            ulong crc = crc32(0, NULL, 0);
            crc = crc32(crc, (const Bytef *)result.data(), result.size());
            QString crc2 = QString(QByteArray::number(~(uint)crc, 16).left(4));

            if (QString::compare(crc1, crc2, Qt::CaseInsensitive) != 0){
                error = true;
                continue;
            }

            return result;
        }
        else
            return QString();
    }
    return QString();
}
开发者ID:MidoriYakumo,项目名称:hippo,代码行数:45,代码来源:jsbridge.cpp

示例7: QMetaMethod_name

static QByteArray QMetaMethod_name(const QMetaMethod &m)
{
    QByteArray sig = m.signature();
    int paren = sig.indexOf('(');
    if (paren == -1)
        return sig;
    else
        return sig.left(paren);
}
开发者ID:fluxer,项目名称:katie,代码行数:9,代码来源:qdeclarativeobjectscriptclass.cpp

示例8: calculateSize

qulonglong TrashSizeCache::calculateSize()
{
    // First read the directorysizes cache into memory
    QFile file( mTrashSizeCachePath );
    typedef QHash<QByteArray, CacheData> DirCacheHash;
    DirCacheHash dirCache;
    if (file.open(QIODevice::ReadOnly)) {
        while (!file.atEnd()) {
            const QByteArray line = file.readLine();
            const int firstSpace = line.indexOf(' ');
            const int secondSpace = line.indexOf(' ', firstSpace + 1);
            CacheData data;
            data.mtime = line.left(firstSpace).toLongLong();
            // "012 4567 name" -> firstSpace=3, secondSpace=8, we want mid(4,4)
            data.size = line.mid(firstSpace + 1, secondSpace - firstSpace - 1).toULongLong();
            dirCache.insert(line.mid(secondSpace + 1), data);
        }
    }
    // Iterate over the actual trashed files.
    // Orphan items (no .fileinfo) still take space.
    QDirIterator it( mTrashPath + QString::fromLatin1( "/files/" ), QDirIterator::NoIteratorFlags );

    qulonglong sum = 0;
    while ( it.hasNext() ) {
        const QFileInfo file = it.next();
        if (file.fileName() == QLatin1String(".") || file.fileName() == QLatin1String("..")) {
            continue;
        }
        if ( file.isSymLink() ) {
            // QFileInfo::size does not return the actual size of a symlink. #253776
            KDE_struct_stat buff;
            return static_cast<qulonglong>(KDE::lstat(file.absoluteFilePath(), &buff) == 0 ? buff.st_size : 0);
        } else if (file.isFile()) {
            sum += file.size();
        } else {
            bool usableCache = false;
            const QString fileId = file.fileName();
            DirCacheHash::const_iterator it = dirCache.constFind(QFile::encodeName(fileId));
            if (it != dirCache.constEnd()) {
                const CacheData &data = *it;
                const QString fileInfoPath = mTrashPath + "/info/" + fileId + ".trashinfo";
                if (QFileInfo(fileInfoPath).lastModified().toMSecsSinceEpoch() == data.mtime) {
                    sum += data.size;
                    usableCache = true;
                }
            }
            if (!usableCache) {
                const qulonglong size = DiscSpaceUtil::sizeOfPath(file.absoluteFilePath());
                sum += size;
                add(fileId, size);
            }
        }

    }

    return sum;
}
开发者ID:KDE,项目名称:kde-runtime,代码行数:57,代码来源:trashsizecache.cpp

示例9: parseRequest

/*!
 * \reimp
 */
QHttpRequestHeader QxtHttpServerConnector::parseRequest(QByteArray& buffer)
{
    int pos = buffer.indexOf("\r\n\r\n"), endpos = pos + 3;
    if (pos == -1)
    {
        pos = buffer.indexOf("\r\n"); // 0.9
        endpos = pos + 1;
    }

    QHttpRequestHeader header(QString::fromUtf8(buffer.left(endpos)));
    QByteArray firstLine = buffer.left(buffer.indexOf('\r'));
    if (firstLine.indexOf("HTTP/") == -1)
    {
        header.setRequest(header.method(), header.path(), 0, 9);
    }
    buffer.remove(0, endpos + 1);
    return header;
}
开发者ID:npsm,项目名称:libqxt,代码行数:21,代码来源:qxthttpserverconnector.cpp

示例10: fromByteArray

bool SimulationOwner::fromByteArray(const QByteArray& data) {
    if (data.size() == NUM_BYTES_ENCODED) {
        QByteArray idBytes = data.left(NUM_BYTES_RFC4122_UUID);
        _id = QUuid::fromRfc4122(idBytes);
        _priority = data[NUM_BYTES_RFC4122_UUID];
        return true;
    }
    return false;
}
开发者ID:MarcelEdward,项目名称:hifi,代码行数:9,代码来源:SimulationOwner.cpp

示例11:

QByteArray & HWProto::addByteArrayToBuffer(QByteArray & buf, const QByteArray & msg)
{
    QByteArray bmsg = msg;
    bmsg = bmsg.left(250);
    quint8 sz = bmsg.size();
    buf.append(QByteArray((char *)&sz, 1));
    buf.append(bmsg);
    return buf;
}
开发者ID:hedgewars,项目名称:hw,代码行数:9,代码来源:proto.cpp

示例12: data

void Cipher_T::testHmacSha1()
{
    QByteArray key = QByteArray::fromHex("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b");
    QByteArray data("Hi There");
    QByteArray digest =
            QByteArray::fromHex("b617318655057264e28bc0b6fb378c8ef146be00");
    QCOMPARE(Cipher::hmacSha1(key, data), digest.left(10));

    key = QByteArray("Jefe");
    data = QByteArray("what do ya want for nothing?");
    digest = QByteArray::fromHex("effcdf6ae5eb2fa2d27416d5f184df9c259a7c79");
    QCOMPARE(Cipher::hmacSha1(key, data), digest.left(10));

    key = QByteArray::fromHex("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
    data = QByteArray(50, 0xdd);
    digest = QByteArray::fromHex("125d7342b9ac11cd91a39af48aa17b4f63f175d3");
    QCOMPARE(Cipher::hmacSha1(key, data), digest.left(10));
}
开发者ID:18062562566,项目名称:libQtShadowsocks,代码行数:18,代码来源:cipher.t.cpp

示例13: splitHeadersAndData

static bool splitHeadersAndData(const QByteArray& request, QByteArray& header, QByteArray& data)
{
    const int sep = request.indexOf("\r\n\r\n");
    if (sep <= 0)
        return false;
    header = request.left(sep);
    data = request.mid(sep + 4);
    return true;
}
开发者ID:nbeudez,项目名称:KDSoap,代码行数:9,代码来源:httpserver_p.cpp

示例14: onENetPeerPacketReceived

void Tunneld::onENetPeerPacketReceived(ENetHost *enhost, ENetPeer *enpeer, int chanid, QByteArray packet)
{
    // ToxTunChannel *chan = this->m_enpeer_chans[enpeer];
    // ToxTunChannel *chan = this->m_conid_chans[(enpeer->data)];
    // ToxTunChannel *chan = (ToxTunChannel*)enpeer->toxchan;
    ToxTunChannel *chan = peerLastChan(enpeer);

    if (packet.length() > 50) {
        // qDebug()<<enhost<<enpeer<<chanid<<packet.length()<<packet.left(20)<<"..."<<packet.right(20);
    } else {
        // qDebug()<<enhost<<enpeer<<chanid<<packet.length()<<packet;
    }

    if (chan == NULL) {
        qDebug()<<"error: chan null:"<<enpeer;
        if (packet.length() > 50) {
            qDebug()<<enhost<<enpeer<<chanid<<packet.length()<<packet.left(20)<<"..."<<packet.right(20);
        } else {
            qDebug()<<enhost<<enpeer<<chanid<<packet.length()<<packet;
        }
        qDebug()<<"drop crash packet, be careful, be true";
        return;
        // 这个断言在外网还是出现比较频繁的。
        assert(1 == 2);
    }
    
    if (chanid == 1) {
        qDebug()<<enhost<<enpeer<<chanid<<packet.length()<<packet;
        if (packet == QByteArray("CLIFIN")) {
            if (chan->peer_sock_closed == false) {
                chan->peer_sock_closed = true;
                chan->peer_sock_close_time = QDateTime::currentDateTime();

                if (chan->sock_closed == false) {
                    // should close myself socket???
                    // 也就是对方不会再发送新的数据过来,也不会再接收数据了,
                    // 但有可能对方的发送缓冲区中还有未发送成功的缓冲数据。
                    // 使用计时器,如果在一定时间内再也没有收到包,则认为对方没有要发送的数据了。
                }
                
                this->promiseChannelCleanup(chan);                
            } else {
                qDebug()<<"maybe duplicate CLIFIN packet:i/o:"
                        <<enpeer->incomingPeerID<<enpeer->outgoingPeerID;
            }
        } else {
            qDebug()<<"invalid chan1 packet:";
        }
        return;
    }

    chan->last_recv_peer_pkt_time = QDateTime::currentDateTime();
    QTcpSocket *sock = chan->m_sock;

    int wrlen = sock->write(packet);
}
开发者ID:kitech,项目名称:toxsh,代码行数:56,代码来源:tunneld.cpp

示例15: readHeaders

void HTTPConnection::readHeaders() {
    while (_socket->canReadLine()) {
        QByteArray line = _socket->readLine();
        QByteArray trimmed = line.trimmed();
        if (trimmed.isEmpty()) {
            _socket->disconnect(this, SLOT(readHeaders()));

            QByteArray clength = requestHeader("Content-Length");
            if (clength.isEmpty()) {
                _parentManager->handleHTTPRequest(this, _requestUrl);

            } else {
                bool success = false;
                auto length = clength.toInt(&success);
                if (!success) {
                    qWarning() << "Invalid header." << _address << trimmed;
                    respond("400 Bad Request", "The header was malformed.");
                    return;
                }

                // Storing big requests in memory gets expensive, especially on servers
                // with limited memory. So we store big requests in a temporary file on disk
                // and map it to faster read/write access.
                static const int MAX_CONTENT_SIZE_IN_MEMORY = 10 * 1000 * 1000;
                if (length < MAX_CONTENT_SIZE_IN_MEMORY) {
                    _requestContent = MemoryStorage::make(length);
                } else {
                    _requestContent = FileStorage::make(length);
                }

                connect(_socket, SIGNAL(readyRead()), SLOT(readContent()));

                // read any content immediately available
                readContent();
            }
            return;
        }
        char first = line.at(0);
        if (first == ' ' || first == '\t') { // continuation
            _requestHeaders[_lastRequestHeader].append(trimmed);
            continue;
        }
        int idx = trimmed.indexOf(':');
        if (idx == -1) {
            qWarning() << "Invalid header." << _address << trimmed;
            respond("400 Bad Request", "The header was malformed.");
            return;
        }
        _lastRequestHeader = trimmed.left(idx).toLower();
        QByteArray& value = _requestHeaders[_lastRequestHeader];
        if (!value.isEmpty()) {
            value.append(", ");
        }
        value.append(trimmed.mid(idx + 1).trimmed());
    }
}
开发者ID:AndrewMeadows,项目名称:hifi,代码行数:56,代码来源:HTTPConnection.cpp


注:本文中的QByteArray::left方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。