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


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

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


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

示例1: parseLabel

ParsedLabel parseLabel(const QByteArray& label)
{
    ParsedLabel ret;
    int functionStart = 0;
    int functionEnd = label.length();
    if (label.startsWith("0x")) {
        int colonPos = label.indexOf(": ");
        if (colonPos != -1) {
            ret.address = label.left(colonPos);
            functionStart = colonPos + 2;
        }
    }
    if (label.endsWith(')')) {
        int locationPos = label.lastIndexOf(" (");
        if (locationPos != -1) {
            ret.location = label.mid(locationPos + 2, label.length() - locationPos - 3);
            functionEnd = locationPos;
        }
    }
    ret.function = label.mid(functionStart, functionEnd - functionStart);
    return ret;
}
开发者ID:KDE,项目名称:massif-visualizer,代码行数:22,代码来源:util.cpp

示例2: start

void ProppatchJob::start()
{
    if (_properties.isEmpty()) {
        qCWarning(lcProppatchJob) << "Proppatch with no properties!";
    }
    QNetworkRequest req;

    QByteArray propStr;
    QMapIterator<QByteArray, QByteArray> it(_properties);
    while (it.hasNext()) {
        it.next();
        QByteArray keyName = it.key();
        QByteArray keyNs;
        if (keyName.contains(':')) {
            int colIdx = keyName.lastIndexOf(":");
            keyNs = keyName.left(colIdx);
            keyName = keyName.mid(colIdx + 1);
        }

        propStr += "    <" + keyName;
        if (!keyNs.isEmpty()) {
            propStr += " xmlns=\"" + keyNs + "\" ";
        }
        propStr += ">";
        propStr += it.value();
        propStr += "</" + keyName + ">\n";
    }
    QByteArray xml = "<?xml version=\"1.0\" ?>\n"
                     "<d:propertyupdate xmlns:d=\"DAV:\">\n"
                     "  <d:set><d:prop>\n"
        + propStr + "  </d:prop></d:set>\n"
                    "</d:propertyupdate>\n";

    QBuffer *buf = new QBuffer(this);
    buf->setData(xml);
    buf->open(QIODevice::ReadOnly);
    sendRequest("PROPPATCH", makeDavUrl(path()), req, buf);
    AbstractNetworkJob::start();
}
开发者ID:uniblockchain,项目名称:client,代码行数:39,代码来源:networkjobs.cpp

示例3: qtCoreFromOtool

static QString qtCoreFromOtool(const QString &path)
{
  QProcess proc;
  proc.setProcessChannelMode(QProcess::SeparateChannels);
  proc.setReadChannel(QProcess::StandardOutput);
  proc.start("otool", QStringList() << "-L" << path);
  proc.waitForFinished();

  forever {
    const QByteArray line = proc.readLine();
    if (line.isEmpty())
      break;

    if (ProbeABIDetector::containsQtCore(line)) {
      const int pos = line.lastIndexOf(" (");
      if (pos <= 0)
        continue;
      return QString::fromLocal8Bit(line.left(pos).trimmed());
    }
  }

  return QString();
}
开发者ID:aleixpol,项目名称:GammaRay,代码行数:23,代码来源:probeabidetector_mac.cpp

示例4: callTargetRemote

void GdbRemoteServerEngine::callTargetRemote()
{
    QByteArray rawChannel = startParameters().remoteChannel.toLatin1();
    QByteArray channel = rawChannel;

    // Don't touch channels with explicitly set protocols.
    if (!channel.startsWith("tcp:") && !channel.startsWith("udp:")
            && !channel.startsWith("file:") && channel.contains(':'))
    {
        // "Fix" the IPv6 case with host names without '['...']'
        if (!channel.startsWith('[') && channel.count(':') >= 2) {
            channel.insert(0, '[');
            channel.insert(channel.lastIndexOf(':'), ']');
        }
        channel = "tcp:" + channel;
    }

    if (m_isQnxGdb)
        postCommand("target qnx " + channel, CB(handleTargetQnx));
    else if (m_isMulti)
        postCommand("target extended-remote " + m_serverChannel, CB(handleTargetExtendedRemote));
    else
        postCommand("target remote " + channel, CB(handleTargetRemote), 10);
}
开发者ID:Revulet,项目名称:qtcreator,代码行数:24,代码来源:remotegdbserveradapter.cpp

示例5: qtCoreFromLdd

static QString qtCoreFromLdd(const QString &path)
{
    QProcess proc;
    proc.setProcessChannelMode(QProcess::SeparateChannels);
    proc.setReadChannel(QProcess::StandardOutput);
    proc.start(QStringLiteral("ldd"), QStringList() << path);
    proc.waitForFinished();

    forever {
        const QByteArray line = proc.readLine();
        if (line.isEmpty())
            break;

        if (ProbeABIDetector::containsQtCore(line)) {
            const int begin = line.indexOf("=> ");
            const int end = line.lastIndexOf(" (");
            if (begin <= 0 || end <= 0 || end <= begin)
                continue;
            return QString::fromLocal8Bit(line.mid(begin + 3, end - begin - 3).trimmed());
        }
    }

    return QString();
}
开发者ID:xhaakon,项目名称:GammaRay,代码行数:24,代码来源:probeabidetector_elf.cpp

示例6: readRequest

void HTTPConnection::readRequest() {
    if (!_socket->canReadLine()) {
        return;
    }
    // parse out the method and resource
    QByteArray line = _socket->readLine().trimmed();
    if (line.startsWith("HEAD")) {
        _requestOperation = QNetworkAccessManager::HeadOperation;

    } else if (line.startsWith("GET")) {
        _requestOperation = QNetworkAccessManager::GetOperation;

    } else if (line.startsWith("PUT")) {
        _requestOperation = QNetworkAccessManager::PutOperation;

    } else if (line.startsWith("POST")) {
        _requestOperation = QNetworkAccessManager::PostOperation;

    } else if (line.startsWith("DELETE")) {
        _requestOperation = QNetworkAccessManager::DeleteOperation;

    } else {
        qWarning() << "Unrecognized HTTP operation." << _address << line;
        respond("400 Bad Request", "Unrecognized operation.");
        return;
    }
    int idx = line.indexOf(' ') + 1;
    _requestUrl.setUrl(line.mid(idx, line.lastIndexOf(' ') - idx));

    // switch to reading the header
    _socket->disconnect(this, SLOT(readRequest()));
    connect(_socket, SIGNAL(readyRead()), SLOT(readHeaders()));

    // read any headers immediately available
    readHeaders();
}
开发者ID:brotchie,项目名称:hifi,代码行数:36,代码来源:HTTPConnection.cpp

示例7: ubuntu_unity_hack_getFinished

void SysTray::ubuntu_unity_hack_getFinished(int exit_code) 
{
    QProcess* get = qobject_cast<QProcess*>(sender());
    if (!get)
      return;

    get->deleteLater();

    if (exit_code != 0) {
      // Probably not running in Unity.
      return;
    }

    QByteArray whitelist = get->readAllStandardOutput();

    Debug::debug() << "Unity whitelist is" << whitelist;

    int index = whitelist.lastIndexOf(']');
    if (index == -1 || whitelist.contains("'yarock'"))
      return;

    whitelist = whitelist.left(index) + QString(", 'yarock'").toUtf8() +
                whitelist.mid(index);

    Debug::debug() << "Setting unity whitelist to" << whitelist;

    QProcess* set = new QProcess(this);
    
    connect(set, SIGNAL(finished(int)), set, SLOT(deleteLater()));
    set->start(kGSettingsFileName, QStringList()
             << "set" << kUnityPanel << kUnitySystrayWhitelist << whitelist);

    Debug::debug() << "Yarock has added itself to the Unity system tray" <<
                      "whitelist, but this won't take effect until the next time" <<
                      "you log out and log back in.";
}
开发者ID:kehugter,项目名称:Yarock,代码行数:36,代码来源:systray.cpp

示例8: get

void CgiProtocol::get( const KUrl& url )
{
  kDebug(7124) << "CgiProtocol::get()";
  kDebug(7124) << " URL: " << url.url();
#if 0
  kDebug(7124) << " Path: " << url.path();
  kDebug(7124) << " Query: " << url.query();
  kDebug(7124) << " Protocol: " << url.protocol();
  kDebug(7124) << " Filename: " << url.filename();
#endif
  QByteArray protocol = "SERVER_PROTOCOL=HTTP";
  putenv( protocol.data() );

  QByteArray requestMethod = "REQUEST_METHOD=GET";
  putenv( requestMethod.data() );

  QByteArray query = url.query().mid( 1 ).toLocal8Bit();
  query.prepend( "QUERY_STRING=" );
  putenv( query.data() );

  QString path = url.path();

  QString file;

  int pos = path.lastIndexOf('/');
  if ( pos >= 0 ) file = path.mid( pos + 1 );
  else file = path;

  QString cmd;

  bool stripHeader = false;
  bool forwardFile = true;

  QStringList::ConstIterator it;
  for( it = mCgiPaths.constBegin(); it != mCgiPaths.constEnd(); ++it ) {
    cmd = *it;
    if ( !(*it).endsWith('/') )
        cmd += '/';
    cmd += file;
    if ( KStandardDirs::exists( cmd ) ) {
      forwardFile = false;
      stripHeader = true;
      break;
    }
  }

  FILE *fd;

  if ( forwardFile ) {
    kDebug(7124) << "Forwarding to '" << path << "'";

    QByteArray filepath = QFile::encodeName( path );

    fd = fopen( filepath.data(), "r" );

    if ( !fd ) {
      kDebug(7124) << "Error opening '" << filepath << "'";
      error(KIO::ERR_CANNOT_OPEN_FOR_READING, path);
      return;
    }
  } else {
    kDebug(7124) << "Cmd: " << cmd;

    fd = popen( QFile::encodeName(KShell::quoteArg( cmd )).data(), "r" );

    if ( !fd ) {
      kDebug(7124) << "Error running '" << cmd << "'";
      error( KIO::ERR_CANNOT_OPEN_FOR_READING, cmd );
      return;
    }
  }

  char buffer[ 4090 ];

  while ( !feof( fd ) )
  {
    int n = fread( buffer, 1, 2048, fd );

    if ( n == -1 )
    {
      // ERROR
      if ( forwardFile ) {
        fclose( fd );
      } else {
        pclose( fd );
      }
      return;
    }

    buffer[n] = 0;

    if ( stripHeader ) {
      QByteArray output = buffer; // this assumes buffer is text and not binary
      int colon = output.indexOf( ':' );
      int newline = output.indexOf( '\n' );
      int semicolon = output.lastIndexOf( ';', newline );
      int end;
      if ( semicolon < 0 ) end = newline;
      else end = semicolon;

//.........这里部分代码省略.........
开发者ID:KDE,项目名称:kde-runtime,代码行数:101,代码来源:cgi.cpp

示例9: if

void tH3000LinkRx::RxSerialData(const QByteArray& rxData)
{
    bool messageReceived = false;

    // Receive buffer is a QByteArray
    // This could be optimised to be char array to reduce allocs and copies
    m_RxBuffer += rxData;

    int endIndex = m_RxBuffer.indexOf("\r\n");

    while(endIndex != -1)
    {
        QByteArray RxMessage = m_RxBuffer.left(endIndex);

        if(RxMessage.size() > 0)
        {
            bool messageOk = false;

#ifdef LOG_H3000_RX
            DbgPrintf("**** H3000 Rx %s", RxMessage.constData());
#endif
            // Check the checksum
            int checksumIndex = RxMessage.lastIndexOf('*');

            if(checksumIndex != -1)
            {
                unsigned char calcChecksum = static_cast<unsigned char>( tH3000Command::CalculateChecksum( RxMessage.left( checksumIndex) ) );
                unsigned char checksum = static_cast<unsigned char>( RxMessage.mid(checksumIndex + 1, 2).toInt(0, 16) );

                if(checksum == calcChecksum)
                {
                    messageOk = true;
                }
            }

            if(messageOk == true)
            {
                QByteArray strippedMessage = RxMessage.left(checksumIndex);

                if(RxMessage.at(0) == '#')
                {
                    emit H3000ReceivedEchoResponse(RxMessage);
                }
                else if(RxMessage.at(0) == 'V')
                {
                    ProcessReceivedValue(strippedMessage);
                }
                else if(RxMessage.at(0) == 'U') 
                {
                    ProcessReceivedTableData(strippedMessage);
                }
                else if(RxMessage.at(0) == 'L')
                {
                    ProcessReceivedPosition(strippedMessage);
                }
                else if(RxMessage.at(0) == 'T')
                {
                    ProcessReceivedUTC(strippedMessage);
                }
                else if(RxMessage.at(0) == 'M')
                {
                    ProcessReceivedTrueMagSetting(strippedMessage);
                }

                messageReceived = true;
            }
        }

        m_RxBuffer = m_RxBuffer.mid(endIndex + 2);

        endIndex = m_RxBuffer.indexOf("\r\n");
    }

    if((messageReceived) && (!m_DataReceived))
    {
        m_DataReceived = true;

        emit H3000LinkDataReceived();
    }
}
开发者ID:dulton,项目名称:53_hero,代码行数:80,代码来源:tH3000LinkRx.cpp

示例10: wrapInFunction


//.........这里部分代码省略.........
// x == "Say no!"
//! [19]


//! [20]
QByteArray ba("colour behaviour flavour neighbour");
ba.replace(QByteArray("ou"), QByteArray("o"));
// ba == "color behavior flavor neighbor"
//! [20]


//! [21]
QByteArray x("sticky question");
QByteArray y("sti");
x.indexOf(y);               // returns 0
x.indexOf(y, 1);            // returns 10
x.indexOf(y, 10);           // returns 10
x.indexOf(y, 11);           // returns -1
//! [21]


//! [22]
QByteArray ba("ABCBA");
ba.indexOf("B");            // returns 1
ba.indexOf("B", 1);         // returns 1
ba.indexOf("B", 2);         // returns 3
ba.indexOf("X");            // returns -1
//! [22]


//! [23]
QByteArray x("crazy azimuths");
QByteArray y("az");
x.lastIndexOf(y);           // returns 6
x.lastIndexOf(y, 6);        // returns 6
x.lastIndexOf(y, 5);        // returns 2
x.lastIndexOf(y, 1);        // returns -1
//! [23]


//! [24]
QByteArray ba("ABCBA");
ba.lastIndexOf("B");        // returns 3
ba.lastIndexOf("B", 3);     // returns 3
ba.lastIndexOf("B", 2);     // returns 1
ba.lastIndexOf("X");        // returns -1
//! [24]


//! [25]
QByteArray url("ftp://ftp.qt-project.org/");
if (url.startsWith("ftp:"))
    ...
//! [25]


//! [26]
QByteArray url("http://qt-project.org/doc/qt-5.0/qtdoc/index.html");
if (url.endsWith(".html"))
    ...
//! [26]


//! [27]
QByteArray x("Pineapple");
QByteArray y = x.left(4);
开发者ID:SchleunigerAG,项目名称:WinEC7_Qt5.3.1_Fixes,代码行数:67,代码来源:src_corelib_tools_qbytearray.cpp

示例11: master

int master(int argc, char **argv)
{
    //master
    LxQt::Application app(argc, argv, true);
    app.setQuitOnLastWindowClosed(false);

    if (1 >= argc)
    {
        usage(QObject::tr("%1: no command to run provided!").arg(app_master));
        return 1;
    } else
    {
        //simple help check
        std::string arg1(argv[1]);
        if ("-h" == arg1 || "--help" == arg1)
        {
            usage();
            return 0;
        } else if ("-v" == arg1 || "--version" == arg1)
        {
            version();
            return 0;
        }
        //any other arguments we simply forward to sudo
    }

    QStringList args = app.arguments();
    //check for provided command is done before
    args.removeAt(0);
    PasswordDialog dlg(args);
    dlg.setModal(true);
    app.setActiveWindow(&dlg);

    QScopedPointer<QProcess> sudo{new QProcess};
    QObject::connect(&dlg, &QDialog::finished, [&sudo, &dlg] (int result)
        {
            if (QDialog::Accepted == result)
            {
                sudo->write(QByteArray{}.append(dlg.password().append('\n')));
            } else
            {
                sudo->terminate();
                if (!sudo->waitForFinished(1000))
                    sudo->kill();
            }
        });

    //start background process -> sudo
    sudo->setProcessChannelMode(QProcess::ForwardedOutputChannel);
    sudo->setReadChannel(QProcess::StandardError);

    QString last_line;
    int ret;
    QObject::connect(sudo.data(), static_cast<void (QProcess::*)(int, QProcess::ExitStatus)>(&QProcess::finished)
            , [&app, &ret, &last_line, &dlg] (int exitCode, QProcess::ExitStatus exitStatus)
        {
            ret = QProcess::NormalExit == exitStatus ? exitCode : 255;
            if (0 != ret && last_line.startsWith(QStringLiteral("%1:").arg(sudo_prog)))
                QMessageBox(QMessageBox::Critical, dlg.windowTitle()
                        , QObject::tr("Child '%1' process failed!\n%2").arg(sudo_prog).arg(last_line), QMessageBox::Ok).exec();
            app.quit();
        });

    QObject::connect(sudo.data(), &QProcess::readyReadStandardError, [&sudo, &dlg, &last_line]
        {
            QByteArray err = sudo->readAllStandardError();
            if (sudo_pwd_prompt == err.constData())
            {
                dlg.show();
                return;
            }

            QTextStream{stderr, QIODevice::WriteOnly} << err;
            int nl_pos = err.lastIndexOf('\n');
            if (-1 == nl_pos)
                last_line += err;
            else
            {
                if (err.endsWith('\n'))
                    err.remove(err.size() - 1, 1);
                nl_pos = err.lastIndexOf('\n');
                if (-1 != nl_pos)
                    err.remove(0, nl_pos + 1);
                last_line = err;
            }
        });

    //forward all stdin to child
    QTextStream std_in{stdin, QIODevice::ReadOnly};
    QSocketNotifier stdin_watcher{0/*stdin*/, QSocketNotifier::Read};
    QObject::connect(&stdin_watcher, &QSocketNotifier::activated, [&std_in, &sudo]
        {
            QString line{std_in.readLine()};
            if (!std_in.atEnd())
                line += QLatin1Char('\n');
            sudo->write(line.toStdString().c_str());
            if (std_in.atEnd())
                sudo->closeWriteChannel();
        });

//.........这里部分代码省略.........
开发者ID:siduction-upstream,项目名称:lxqt-sudo,代码行数:101,代码来源:main.cpp

示例12: metaDataChanged

void DownloadItem::metaDataChanged()
{
    // https://tools.ietf.org/html/rfc6266
    if (m_reply->hasRawHeader(QByteArray("Content-Disposition"))) {
        QByteArray header = m_reply->rawHeader(QByteArray("Content-Disposition"));
        int index = header.indexOf("filename=");
        if (index >= 0) {
            header = header.mid(index+9);
            if (header.startsWith("\"") || header.startsWith("'"))
                header = header.mid(1);
            if ((index = header.lastIndexOf("\"")) > 0)
                header = header.left(index);
            else if ((index = header.lastIndexOf("'")) > 0)
                header = header.left(index);
            m_fileName = QUrl::fromPercentEncoding(header);
        }
        // Sometimes "filename=" and "filename*=UTF-8''" is set.
        // So, search for this too.
        index = header.indexOf("filename*=UTF-8''");
        if (index >= 0) {
            header = header.mid(index+17);
            if (header.startsWith("\"") || header.startsWith("'"))
                header = header.mid(1);
            if ((index = header.lastIndexOf("\"")) > 0)
                header = header.left(index);
            else if ((index = header.lastIndexOf("'")) > 0)
                header = header.left(index);
            m_fileName = QUrl::fromPercentEncoding(header);
        }
    }

    QUrl url = m_reply->url();

    // If this is a redirected url use this instead
    QUrl redirectUrl = m_reply->attribute(QNetworkRequest::RedirectionTargetAttribute).toUrl();
    if (!redirectUrl.isEmpty()) {
        QString s = redirectUrl.toString();
        std::cout << "Redirected to " << s.toStdString() << std::endl;

        QVariant header = m_reply->header(QNetworkRequest::LocationHeader);
        QString loc = header.toString();
        Q_UNUSED(loc);

        if (url != redirectUrl) {
            url = redirectUrl;

            if (m_reply) {
                disconnect(m_reply, SIGNAL(readyRead()), this, SLOT(downloadReadyRead()));
                disconnect(m_reply, SIGNAL(error(QNetworkReply::NetworkError)),
                           this, SLOT(error(QNetworkReply::NetworkError)));
                disconnect(m_reply, SIGNAL(downloadProgress(qint64, qint64)),
                           this, SLOT(downloadProgress(qint64, qint64)));
                disconnect(m_reply, SIGNAL(metaDataChanged()),
                           this, SLOT(metaDataChanged()));
                disconnect(m_reply, SIGNAL(finished()),
                           this, SLOT(finished()));
                m_reply->close();
                m_reply->deleteLater();
            }

            m_reply = DownloadManager::getInstance()->networkAccessManager()->get(QNetworkRequest(url));
            init();
        }
    }
}
开发者ID:DevJohan,项目名称:FreeCAD_sf_master,代码行数:65,代码来源:DownloadItem.cpp

示例13: connect

// Connect up a particular slot name, with optional arguments.
static void connect(QObject *qobj, PyObject *slot_obj,
        const QByteArray &slot_nm, const QByteArray &args)
{
    // Ignore if it's not an autoconnect slot.
    if (!slot_nm.startsWith("on_"))
        return;

    // Extract the names of the emitting object and the signal.
    int i;

    i = slot_nm.lastIndexOf('_');

    if (i - 3 < 1 || i + 1 >= slot_nm.size())
        return;

    QByteArray ename = slot_nm.mid(3, i - 3);
    QByteArray sname = slot_nm.mid(i + 1);

    // Find the emitting object and get its meta-object.
#if defined(QT_NO_MEMBER_TEMPLATES)
    QObject *eobj = qFindChild<QObject *>(qobj, ename);
#else
    QObject *eobj = qobj->findChild<QObject *>(ename);
#endif

    if (!eobj)
        return;

    const QMetaObject *mo = eobj->metaObject();

    // Got through the methods looking for a matching signal.
    PyObject *epyobj = 0;

    for (int m = 0; m < mo->methodCount(); ++m)
    {
        QMetaMethod mm = mo->method(m);

        if (mm.methodType() != QMetaMethod::Signal)
            continue;

#if QT_VERSION >= 0x050000
        QByteArray sig(mm.methodSignature());
#else
        QByteArray sig(mm.signature());
#endif

        if (Chimera::Signature::name(sig) != sname)
            continue;

        // If we have slot arguments then they must match as well.
        if (!args.isEmpty() && Chimera::Signature::arguments(sig) != args)
            continue;

        // Add the type character.
        sig.prepend('2');

        // Get the wrapper now we know it is needed.
        if (!epyobj)
        {
            epyobj = sipConvertFromType(eobj, sipType_QObject, 0);

            if (!epyobj)
                break;
        }

        // Connect the signal.
        PyObject *res = sipConnectRx(epyobj, sig.constData(), slot_obj, 0, 0);
        Py_XDECREF(res);
    }

    Py_XDECREF(epyobj);
}
开发者ID:AlexDoul,项目名称:PyQt4,代码行数:73,代码来源:qpycore_qmetaobject_helpers.cpp

示例14: mandir

char *MANProtocol::readManPage(const char *_filename)
{
    QByteArray filename = _filename;
    QByteArray array;

    /* Determine type of man page file by checking its path. Determination by
     * MIME type with KMimeType doesn't work reliablely. E.g., Solaris 7:
     * /usr/man/sman7fs/pcfs.7fs -> text/x-csrc : WRONG
     * If the path name constains the string sman, assume that it's SGML and
     * convert it to roff format (used on Solaris). */
    //QString file_mimetype = KMimeType::findByPath(QString(filename), 0, false)->name();
    if (QString(filename).contains("sman", Qt::CaseInsensitive)) //file_mimetype == "text/html" || )
    {
        KProcess proc;
        // Determine path to sgml2roff, if not already done.
        getProgramPath();
        proc << mySgml2RoffPath << filename;
        proc.setOutputChannelMode( KProcess::OnlyStdoutChannel );
        proc.execute();
        array = proc.readAllStandardOutput();
    }
    else
    {
      if (QDir::isRelativePath(filename))
      {
          qCDebug(KIO_MAN_LOG) << "relative " << filename;
          filename = QDir::cleanPath(lastdir + '/' + filename).toUtf8();
          qCDebug(KIO_MAN_LOG) << "resolved to " << filename;
      }

      lastdir = filename.left(filename.lastIndexOf('/'));

      if ( !QFile::exists(QFile::decodeName(filename)) )  // if given file does not exist, find with suffix
      {
          qCDebug(KIO_MAN_LOG) << "not existing " << filename;
          QDir mandir(lastdir);
          mandir.setNameFilters(QStringList() << (filename.mid(filename.lastIndexOf('/') + 1) + ".*"));
          filename = lastdir + '/' + QFile::encodeName(mandir.entryList().first());
          qCDebug(KIO_MAN_LOG) << "resolved to " << filename;
      }

      QIODevice *fd = KFilterDev::deviceForFile(filename);

      if ( !fd || !fd->open(QIODevice::ReadOnly))
      {
         delete fd;
         return 0;
      }
      array = fd->readAll();
      qCDebug(KIO_MAN_LOG) << "read " << array.size();
      fd->close();
      delete fd;
    }

    if (array.isEmpty())
      return 0;

    // as we do not know in which encoding the man source is, try to automatically
    // detect it and always return it as UTF-8
    KEncodingProber encodingProber;
    encodingProber.feed(array);
    qCDebug(KIO_MAN_LOG) << "auto-detect encoding for" << filename << "guess=" << encodingProber.encoding()
                 << "confidence=" << encodingProber.confidence();
    QString out = QTextCodec::codecForName(encodingProber.encoding())->toUnicode(array);
    array = out.toUtf8();

    const int len = array.size();
    char *buf = new char[len + 4];
    memmove(buf + 1, array.data(), len);
    buf[0] = buf[len+1] = '\n'; // Start and end with an end of line
    buf[len+2] = buf[len+3] = '\0'; // Two NUL characters at end

    return buf;
}
开发者ID:KDE,项目名称:kio-extras,代码行数:74,代码来源:kio_man.cpp

示例15: slotReplyFin

//-------------------------------------------------------------------------------------------------
void ExchangeRate::slotReplyFin(QNetworkReply *netrep)
{
    if (netrep->error())
    {
        QMessageBox::warning(this, 0, tr("Connection error:") + ' ' + netrep->errorString());
        return;
    }

    const QByteArray baRead = netrep->readAll();
    int iSep = baRead.indexOf("<a href=\"/control/en/curmetal/detail/currency?period=daily\">", 40000);
    if (iSep > 0)
    {
        iSep = baRead.lastIndexOf("</td>", iSep);
        if (iSep > 0)
        {
            const QString strDate = baRead.mid(iSep-10, 10);        //[10 = "dd.MM.yyyy"]
            if (QDateTime::fromString(strDate, "dd.MM.yyyy").isValid())
            {
                iSep = baRead.indexOf("<td class=\"attribute\">100&nbsp;US Dollar</td>", iSep+70);
                if (iSep > 0)
                {
                    iSep = baRead.indexOf("<td class=\"value\" nowrap=\"nowrap\">", iSep+45);
                    if (iSep > 0)
                    {
                        iSep += 34;
                        int iEnd = baRead.indexOf('\n', iSep);
                        if (iEnd > 0)
                        {
                            const double dPerUsd = baRead.mid(iSep, iEnd-iSep-1).toDouble();
                            if (dPerUsd > 300.0 && dPerUsd < 8000.0)
                            {
                                iSep = baRead.indexOf("<td class=\"attribute\">100&nbsp;EURO</td>", iSep+100);
                                if (iSep > 0)
                                {
                                    iSep = baRead.indexOf("<td class=\"value\" nowrap=\"nowrap\">", iSep+40);
                                    if (iSep > 0)
                                    {
                                        iSep += 34;
                                        iEnd = baRead.indexOf('\n', iSep);
                                        if (iEnd > 0)
                                        {
                                            const double dPerEur = baRead.mid(iSep, iEnd-iSep-1).toDouble();
                                            if (dPerEur > 300.0 && dPerEur < 8000.0)
                                            {
                                                iSep = baRead.indexOf("<td class=\"attribute\">10&nbsp;Russian ruble</td>", iSep+100);
                                                if (iSep > 0)
                                                {
                                                    iSep = baRead.indexOf("<td class=\"value\" nowrap=\"nowrap\">", iSep+48);
                                                    if (iSep > 0)
                                                    {
                                                        iSep += 34;
                                                        iEnd = baRead.indexOf('\n', iSep);
                                                        if (iEnd > 0)
                                                        {
                                                            const double dPerRub = baRead.mid(iSep, iEnd-iSep-1).toDouble();
                                                            if (dPerRub > 1.0 && dPerRub < 10.0)
                                                            {
                                                                iSep = 0;
                                                                dUahPerUsd = dPerUsd/100.0;
                                                                dUahPerEur = dPerEur/100.0;
                                                                dUahPerRub = dPerRub/10.0;

                                                                const QString strUahPerUsd = QString::number(dUahPerUsd, 'f', 6),
                                                                        strUahPerEur = QString::number(dUahPerEur, 'f', 6),
                                                                        strUahPerRub = QString::number(dUahPerRub, 'f', 5);

                                                                lblNote->setText(strDate + "\n1 USD = " + strUahPerUsd + " UAH\n1 EUR = " + strUahPerEur + " UAH\n1 UAH = " + QString::number(1.0/dUahPerRub, 'f', 6) + " RUB");

                                                                QSettings stg(strAppStg, QSettings::IniFormat);
                                                                stg.beginGroup("Settings");
                                                                stg.setValue("DateTime", strDate);
                                                                stg.setValue("USD", strUahPerUsd);
                                                                stg.setValue("EUR", strUahPerEur);
                                                                stg.setValue("RUB", strUahPerRub);
                                                                stg.endGroup();

                                                                lblInfo->setText(tr("Successfully"));
                                                                gbMain->setEnabled(true);
                                                                QTimer::singleShot(1300, lblInfo, SLOT(clear()));
                                                            }
                                                            else
                                                                iSep = 114;
                                                        }
                                                        else
                                                            iSep = 113;
                                                    }
                                                    else
                                                        iSep = 112;
                                                }
                                                else
                                                    iSep = 111;
                                            }
                                            else
                                                iSep = 110;
                                        }
                                        else
                                            iSep = 109;
                                    }
                                    else
//.........这里部分代码省略.........
开发者ID:korha,项目名称:ExchangeRateUah,代码行数:101,代码来源:exchangerateuah.cpp


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