Пример #1
0
// Qt4 code
void printMsgHandler(QtMsgType type, const char * _str)
{
    static QMutex _logmut;
    _logmut.lock();
    QString time=QTime::currentTime().toString("hh:mm:ss");
    QString str=QString("[%1]["+time+"] %2\n").arg(type).arg(_str);

    switch (type)
    {
        case QtDebugMsg:
            _logfile.write(str.toLocal8Bit());
            _logfile.flush();
        break;
        case QtWarningMsg:
            fprintf(stderr, "Debug: %s\n", str.toLocal8Bit().data());
            _logfile.write(str.toLocal8Bit());
            _logfile.flush();
        break;
        case QtCriticalMsg:
            _logfile.write(str.toLocal8Bit());
            _logfile.flush();
        break;
        case QtFatalMsg:
            _logfile.write(str.toLocal8Bit());
            _logfile.flush();
            exit(-1);
        break;
    }
    _logmut.unlock();
};
Пример #2
0
void QxtDaemon::messageHandler(QtMsgType type, const char *msg)
{
    QFile * f = qxt_daemon_singleton->logfile;
    f->write("[");
    f->write(QDateTime::currentDateTime().toString(Qt::ISODate).toLocal8Bit());
    f->write("] ");
    if (type == QtDebugMsg)
        f->write("[qDebug] ");
    else if (type == QtWarningMsg)
        f->write("[qWarning] ");
    else if (type == QtCriticalMsg)
        f->write("[qCritical] ");
    else if (type == QtFatalMsg)
    {
        f->write("[qFatal] ");
        f->write(msg);
        f->write("\n");
        f->write("aborting \n");
        f->flush();
        abort();
    }

    f->write(msg);
    f->write("\n");
    f->flush();
}
Пример #3
0
void UpdateManager::DownloadUpdate()
{
    QNetworkAccessManager *manager = new QNetworkAccessManager(this);
    connect(manager, &QNetworkAccessManager::finished,
            [=](QNetworkReply *reply)
            {
                if(reply->error())
                    emit errorSignal("UpdateManager: "+reply->errorString());
                else
                {
                    // todo: progress bar
                    // todo: compression
                    QFile *file = new QFile("Baka MPlayer.exe");
                    if(file->open(QFile::Truncate))
                    {
                        file->write(reply->readAll());
                        file->flush();
                        file->close();
                    }
                    delete file;
                }
                reply->deleteLater();
            });
    manager->get(QNetworkRequest(QUrl("http://bakamplayer.u8sand.net/Baka MPlayer.exe")));
}
Пример #4
0
void ConfigFile::SaveFile(QString path)
{
    QString current = QDir::currentPath();
    QString destinyFile;
    QStringList list = ConfigFileName.split(QDir::separator());
    QString fileName = list.at(list.count()-1);
    if(path!=""){
        //destinyFile = current + QDir::separator() + path + QDir::separator() + fileName;
        destinyFile = path + QDir::separator() + fileName;
    } else {
        destinyFile = current + QDir::separator() + fileName;
    }
    destinyFile = destinyFile.replace("/", QDir::separator());
    destinyFile = destinyFile.replace("\\", QDir::separator());

    DeleteOldFileIfExists(destinyFile);
    QFile *file = OpenFileForWriting(destinyFile);
    if (!file){
        saveSuccess = false;
        return;
    }

    std::string str = this->ConfigContents.toStdString();
    file->write(str.c_str());
    file->flush();
    file->close();
    saveSuccess=true;
}
Пример #5
0
void HttpClient::download(const QString &destinationPath,
                          std::function<void (const QString &)> successHandler,
                          std::function<void (const QString &)> errorHandler) {
    bool  debug = d->debug;
    QFile *file = new QFile(destinationPath);

    if (file->open(QIODevice::WriteOnly)) {
        download([=](const QByteArray &data) {
            file->write(data);
        }, [=](const QString &) {
            // 请求结束后释放文件对象
            file->flush();
            file->close();
            file->deleteLater();

            if (debug) {
                qDebug().noquote() << QString("下载完成,保存到: %1").arg(destinationPath);
            }

            if (nullptr != successHandler) {
                successHandler(QString("下载完成,保存到: %1").arg(destinationPath));
            }
        }, errorHandler);
    } else {
        // 打开文件出错
        if (debug) {
            qDebug().noquote() << QString("打开文件出错: %1").arg(destinationPath);
        }

        if (nullptr != errorHandler) {
            errorHandler(QString("打开文件出错: %1").arg(destinationPath));
        }
    }
}
Пример #6
0
int QMacPasteboardMimeQt3Any::registerMimeType(const QString &mime)
{
    if(!mime_registry.contains(mime)) {
        if(!loadMimeRegistry()) {
            qWarning("QMacPasteboardMimeAnyQt3Mime: Internal error");
            return 0;
        }
        if(!mime_registry.contains(mime)) {
            if(!library_file.isOpen()) {
                if(!library_file.open(QIODevice::WriteOnly)) {
                    qWarning("QMacPasteboardMimeAnyQt3Mime: Failure to open %s -- %s", library_file.fileName().toLatin1().constData(),
                             library_file.errorString().toLatin1().constData());
                    return false;
                }
            }
            int ret = ++current_max;
            mime_registry_loaded = QFileInfo(library_file).lastModified();
            QTextStream stream(&library_file);
            stream << mime << endl;
            stream << ret << endl;
            mime_registry.insert(mime, ret);
            library_file.flush(); //flush and set mtime
            return ret;
        }
    }
    return mime_registry[mime];
}
Пример #7
0
void Downloader::replyFinished (QNetworkReply *reply){
    if(reply->error()){
        qDebug() << "ERROR!";
        m_stat = "ERROR!";
        qDebug() << reply->errorString();
    }else{
        qDebug() << reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toString();

        //QString name = m_image;
        //make the directory here
        QDir dir;
        bool ok = dir.mkpath(m_path);

        if(ok){
            QFile *file = new QFile(m_path + m_image);
            if(file->open(QFile::Append)) {
                file->write(reply->readAll());
                file->flush();
                file->close();
                m_stat = "FINISHED";
            }
            delete file;
        }

    }
    reply->deleteLater();
}
Пример #8
0
/*!
 *\~english
 *	Writes text to log.
 *\~russian
 *	Пишет текст в лог.
 *\~
 *	\param log_name - \~english Full path to logfile \~russian Полный путь к лог файлу \~
 *	\param test_name - \~english Test name \~russian Имя теста \~
 *	\param status - \~english OK, ERROR or SKIP \~russian OK, ОШИБКА или ПРОПУЩЕН \~
 *	\param text - \~english Comment \~russian Комментарий \~
*/
void
aTests::print2log(	const QString &log_name,
			const QString &test_name,
			const QString &status,
			const QString &text)
{
	QString toWrite = QString("%1::%2::%3::%4\r\n")\
			  .arg(QDateTime::currentDateTime().toString(Qt::ISODate).replace('T',' '))\
			  .arg(test_name)\
			  .arg(status)\
			  .arg(text);

	QFile f;
	if(log_name==QString::null)
	{
		f.open( QIODevice::WriteOnly, stdout );
		f.writeBlock((const char*)toWrite,strlen((const char*)toWrite));
	}
	else
	{
		f.setName(log_name);
		f.open( QIODevice::WriteOnly | QIODevice::Append );
		f.writeBlock((const char*)toWrite,strlen((const char*)toWrite));
		f.flush();
	}
	f.close();

//	else printf("error write to log\n");
}
bool TextHelper::writeBatteryPar(QString batteryPar)
{
    QFile *dtsFile = new QFile(Global::srcPath + "/" + Global::dtsPath);
    QFile *tempFile = new QFile(QDir::currentPath() + "/tmp/temp.txt");
    QTextStream dtsTS(dtsFile);
    QTextStream tempTS(tempFile);
    if(!dtsFile->open(QIODevice::ReadOnly))
    {
        qDebug() << Global::srcPath + "/" + Global::dtsPath << " open fail";
        return false;
    }
    if(!tempFile->open(QIODevice::WriteOnly))
    {
        qDebug() << QDir::currentPath() + "/tmp/temp.txt" << " open fail";
        dtsFile->close();
        return false;
    }
    QString strLine;
    while (!dtsTS.atEnd())
    {
        strLine = dtsTS.readLine();
        if(strLine.contains("battery {"))
        {
            tempTS << strLine << "\n";
            strLine = dtsTS.readLine();
            tempTS << strLine << "\n";
            tempTS << "      ocv_table = <";
            QStringList strList = batteryPar.trimmed().split(" ");
            for(int i = 1; i < 21; i++)
            {
                tempTS << strList[i -1] << " ";
                if(i%7 == 0)
                {
                    tempTS << "\n\t\t\t";
                }
            }
            tempTS << strList[20];
            tempTS << ">;\n";
            dtsTS.readLine();
            dtsTS.readLine();
            dtsTS.readLine();
            continue;
        }
        tempTS << strLine << "\n";
    }
    dtsFile->close();
    tempFile->flush();
    tempFile->close();
    if(!dtsFile->remove())
    {
        qDebug() << "dtsFile remove fail";
        return false;
    }
    if(!tempFile->copy(Global::srcPath + "/" + Global::dtsPath))
    {
        qDebug() << "copy fail" << Global::srcPath + "/" + Global::dtsPath;
        return false;
    }
    return true;
}
Пример #10
0
void Scanner::onDownload(QNetworkReply* reply)
{
    qDebug() << "onDownload";
    m_active = false;

    if(reply->error() != QNetworkReply::NoError) {
        qDebug() << reply->errorString();
        return;
    }

    qDebug() << "saving " << reply->url().toString();
    QString random = (QString) qrand();
    QString path = m_path + reply->url().fileName();

    QFile* file = new QFile(path);
    if(file->open(QIODevice::WriteOnly)) {
        file->write(reply->readAll());
    }
    file->flush();
    file->close();
    delete file;
    file = 0;

    if(!downloadQueue.isEmpty())
        BeginDownload();

    return;
}
Пример #11
0
void GameBoard::Menu()
{
    QDialog *menu = new QDialog;
    QLabel *texto = new QLabel;
    QLabel *title = new QLabel("<b><big>Atalhos</big></b>");

    QFile *config = new QFile("/home/vinicius/svn/unball/estrategia/visualization/Visualization Last Version/Visualization_last/Tabela.txt"); //Colocar o diretório ao qual se encontra o arquivo Tabela.txt

    if(!config->open(QFile::ReadOnly | QFile::Text))
    {
        return;
    }
    QTextStream mOut(config);
    QString mTexto = mOut.readAll();


    texto->setText(mTexto);

    QVBoxLayout *lay =new QVBoxLayout;
    lay->addWidget(title);
    lay->addWidget(texto);

    menu->setLayout(lay);
    menu->show();

    config->flush();
    mOut.flush();
    config->close();

}
Пример #12
0
void PortGroup::processViewCaptureAck(PbRpcController *controller)
{
    QFile *capFile = static_cast<QFile*>(controller->binaryBlob());

    QString viewer = appSettings->value(kWiresharkPathKey, 
            kWiresharkPathDefaultValue).toString();

    qDebug("In %s", __FUNCTION__);

    capFile->flush();
    capFile->close();

    if (!QFile::exists(viewer))
    {
        QMessageBox::warning(NULL, "Can't find Wireshark", 
                viewer + QString(" does not exist!\n\nPlease correct the path"
                " to Wireshark in the Preferences."));
        goto _exit;
    }

    if (!QProcess::startDetached(viewer, QStringList() << capFile->fileName()))
        qDebug("Failed starting Wireshark");

_exit:
    delete controller;
}
Пример #13
0
void Global::save(QString filename)
{
  GASSERT(_db != NULL, "Cannot save empty database");

  QFile fd (filename);
  if (!fd.open(QIODevice::WriteOnly))
    GEXITDIALOG("Could not open project file for writing " + filename);
  QTextStream file (&fd);

  file << "VERSION=" << DB_VERSION << "\n";
  file << "IMAGE_PATH=.\n"; // Images are always in the same directory as the project file
  file << "QUESTIONS_PER_STUDENT=" << Global::db()->getNumQuestions() << "\n";
  GASSERT(_numPagesPerStudent > 0, "_numPagesPerStudent %zu is not valid", _numPagesPerStudent);
  file << "PAGES_PER_STUDENT=" << _numPagesPerStudent << "\n";
  file << "TOTAL_STUDENTS=" << Global::db()->getNumStudents() << "\n";
  file << "SAVE_DATE_TIME=" << QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss") << "\n";
  file << "NUM_IMAGES=" << Global::getPages()->size() << "\n";
  if (Global::getPages()->size() != Global::db()->getNumStudents() * _numPagesPerStudent)
  {
    GDEBUG("Detected mismatch in number of pages %zu, number of students %zu, and number of pages per student %zu",
           Global::getPages()->size(), Global::db()->getNumStudents(), _numPagesPerStudent);
    GINFODIALOG("Detected page mismatch during save, but will continue anyway");
  }

  file << "-2\tPAGE\tPAGE\t" << -1;
  for (size_t q = 0; q < Global::db()->getNumQuestions(); q++)
    file << "\t" << Global::db()->getQuestionPage(q);
  for (size_t q = 0; q < Global::db()->getNumQuestions(); q++)
    file << "\t" << "NF"; // Emit empty feedback columns
  file << "\n";

  file << "-1\tMAX\tMAX\t" << Global::db()->getTotalMaximum();
  for (size_t q = 0; q < Global::db()->getNumQuestions(); q++)
    file << "\t" << Global::db()->getQuestionMaximum(q);
  for (size_t q = 0; q < Global::db()->getNumQuestions(); q++)
    file << "\t" << "NF"; // Emit empty feedback columns
  file << "\n";

  for (size_t s = 0; s < Global::db()->getNumStudents(); s++)
  {
    Student& student = Global::db()->getStudent(s);
    file << s << "\t" << student.getStudentId() << "\t" << student.getStudentName();
    file << "\t" << student.getTotal();
    for (size_t q = 0; q < Global::db()->getNumQuestions(); q++)
      file << "\t" << student.getGrade(q);
    for (size_t q = 0; q < Global::db()->getNumQuestions(); q++)
      file << "\t" << student.getFeedback(q);
    file << "\n";
  }

  // Verify that the write actually worked ok
  fd.flush();
  if (fd.error() != QFile::NoError)
    GINFODIALOG ("Failed to write out complete project file - will not exit, but you need to re-save your work!");
  fd.close();

  // TODO: We could also dump out the Qt table as well as a backup in a different file
}
Пример #14
0
void cLogFile::writeLog(QString msg)
{

    QString date = myLocaltime.currentDateTime().toLocalTime().toString( "yyyy.MM.dd_hh:mm:ss" );
    QByteArray log;
    log = QByteArray((date+";"+msg+"\n").toUtf8());
    file.write(log);
    file.flush();

}
Пример #15
0
/* used for scripting IPC
    accepts an open writable file.
    returns false on failure */
bool Matrix::saveToTmpFile(QFile &fp) {
  qint64 n_written;
  qint64 n_write;

  n_write = _nX*_nY*sizeof(double);

  n_written = fp.write((char *)_z, n_write);

  fp.flush();

  return (n_write == n_written);
}
Пример #16
0
void Robotino::writeFileHeader(QFile& file)
{
  file.write("action:5\n");
  file.write("distance:9\n");
  file.write("accel:3\n");
  file.write("current:3\n");
  file.write("power:2\n");
  file.write("bumper:1\n");
  file.write("audio:16\n");
  file.write("end\n");
  file.flush();
}
Пример #17
0
void ZGui::saveAs ( const QString fileName, bool save )
{ 
	if ( (access(fileName.utf8(),0) == 0) && !save )
	{
		QString sBody = lng->getString("REWRITE").arg ( getFileName(fileName) );
		
		ZMessageDlg * pConfirmation = new ZMessageDlg ( lng->getString("SAVING"), sBody, ( ZMessageDlg::MessageDlgType )1, 0, this, "2", true, 0 );
		if ( pConfirmation->exec() )
		{
			ZMessageDlg * pMessage = new ZMessageDlg ( lng->getString("SAVING"), lng->getString("CHANGED"), ( ZMessageDlg::MessageDlgType )1, 0, this, "saveas", true, 0 );
			pMessage->show();
			delete pMessage;
		}
		
		delete pConfirmation;
	}
	
	if ( !(access(getFilePath(fileName).utf8(),02) == 0) ) // Check save to ReadOnly FS
	{   
		ZMessageDlg * pWarning = new ZMessageDlg ( lng->getString("ERROR"), "Do not save to ReadOnly FS!", ( ZMessageDlg::MessageDlgType )2, 0, this, "saveas", true, 0 );
		pWarning->exec();
		delete pWarning;
		return;
	}
	
	if ( access(fileName.utf8(),0) == 0 ) //remove file for rewrite
		remove(fileName.utf8());
	
	QFile file ( fileName );
	
	if ( !file.open ( IO_WriteOnly | IO_Truncate ) )
	{   
		ZMessageDlg * pWarning = new ZMessageDlg ( lng->getString("ERROR"), lng->getString("FILE_SAVING_FAILED"), ( ZMessageDlg::MessageDlgType )2, 0, this, "saveas", true, 0 );
		pWarning->exec();
		delete pWarning;
		return;
	}
	
	QTextCodec* codec = codecByLocalId(textCode);	
	file.reset();
	QCString str = codec->fromUnicode( edit->text() );
	file.writeBlock( str, str.length() );
	char endFile[]={0};
	file.writeBlock( endFile, sizeof(endFile) );
	
	file.flush();
	file.close();
	
	ZMessageDlg * pMessage = new ZMessageDlg ( lng->getString("SAVING"), lng->getString("FILE_SAVING_SUCCESS"), ( ZMessageDlg::MessageDlgType ) 2, 0, this, "saveas", true, 0 );
	pMessage->exec();
	delete pMessage;
}
Пример #18
0
static void tSystemMessage(int priority, const char *msg, va_list ap)
{
    static QSystemSemaphore semaphore("TreeFrogSystemLog", 1, QSystemSemaphore::Open);
    TLog log(priority, QString().vsprintf(msg, ap).toLocal8Bit());
    QByteArray buf = TLogger::logToByteArray(log, syslogLayout, syslogDateTimeFormat);

    semaphore.acquire();  // Acquires the semaphore for system log
    if (!systemLog.fileName().isEmpty() && systemLog.open(QIODevice::WriteOnly | QIODevice::Append | QIODevice::Text)) {
        systemLog.write(buf.data());
        systemLog.flush();
        systemLog.close();
    }
    semaphore.release();  // Releases the semaphore
}
Пример #19
0
 virtual bool setCookiesFromUrl(const QList<QNetworkCookie> &cookieList, const QUrl &url)
 {
     QByteArray data;
     QDataStream dstream(&data, QIODevice::ReadWrite);
     qint32 c = cookieList.count();
     dstream << c;
     qDebug() << cookieList.count();
     for (int i = 0; i < c; ++i)
         dstream << cookieList[i].toRawForm();
     dstream.device()->close();
     stream << QString("setCookiesFromUrl") << url << data;// << cookieList;
     bool set = NetworkCookieJar::setCookiesFromUrl(cookieList, url);
     file.flush();
     return set;
 }
bool TextHelper::enableCam(int camId, QString dtsPath)
{
    QFile   *dtsFile =  new QFile(dtsPath);
    QFile   *newDtsFile = new QFile(QDir::currentPath() + "/tmp/Sofia3GR-tablet.dts");
    QTextStream newDts(newDtsFile);
    QTextStream dtsOld(dtsFile);
    QString strLine;
    if(!dtsFile->open(QIODevice::ReadOnly))
    {
        qDebug() << "dtsFile open fail  enableCam";
        return false;
    }
    if(!newDtsFile->open(QIODevice::WriteOnly))
    {
        qDebug() << "newDtsFile open fail  enableCam";
        dtsFile->close();
        return false;
    }
    while(!dtsOld.atEnd())
    {
        strLine = dtsOld.readLine();
        if(strLine.contains("camera" + QString::number(camId, 10)) && strLine.contains(":"))
        {
               newDts << strLine << "\n";
               newDts << "\t\t//status = \"disabled\";\n";
               strLine = dtsOld.readLine();
               continue;
        }
        newDts << strLine << "\n";
    }
    dtsFile->close();
    newDtsFile->flush();
    newDtsFile->close();

    if(!dtsFile->remove())
    {
        qDebug() << "remove dtsFile fail enableCam";
        return false;
    }
    if(!newDtsFile->copy(dtsPath))
    {
        qDebug() << "camId: " << camId << "file copy fail!!!(enableCam)";
        return false;
    }
    return true;
}
Пример #21
0
void downloader::finishDownload(QNetworkReply *reply)
{
    QByteArray rawData =  reply->readAll();
    reply->destroyed(this);
    QString rawHtml(rawData), HtmlToProcess;

    QFile *file = new QFile(path);

    if(file->open(QFile::Append))
    {
        file->write(rawData);
        file->flush();
        file->close();
    }

    HtmlToProcess = HTMLRemover(rawHtml,"script");
    render(HtmlToProcess);
}
Пример #22
0
void saveBanList()
{
    QString banlist;
    g_pApp->getLocalKvircDirectory(banlist, KviApplication::ConfigPlugins);
    banlist += g_pBanListFilename;
    QFile file;
    file.setFileName(banlist);
    file.open(QIODevice::WriteOnly);

    QTextStream stream(&file);

    stream << g_pBanList->count() << endl;
    for(QString * tmp = g_pBanList->first(); tmp; tmp = g_pBanList->next())
    {
        stream << *tmp << endl;
    }
    file.flush();
    file.close();
}
Пример #23
0
void ConfigFile::SaveFileWithAbsolutePath(QString path)
{
    path = path.replace("/", QDir::separator());
    path = path.replace("\\", QDir::separator());

    DeleteOldFileIfExists(path);

    QFile *file = OpenFileForWriting(path);
    if (!file){
        saveSuccess = false;
        return;
    }

    std::string str = this->ConfigContents.toStdString();
    file->write(str.c_str());
    file->flush();
    file->close();
    saveSuccess=true;
}
void YubiKeyLogger::logConfig(YubiKeyConfig *ykConfig) {
    //Check if logging is enabled
    if(!m_enabled) {
        return;
    }

    QFile *file = getLogFile();
    if(file == NULL) {
        return;
    }

    QTextStream out(file);

    QString format = "";
    if(m_format == Format_Traditional) {
        if(m_started) {
            format += "LOGGING START,{timestampLocal}{endl}";
            m_started = false;
        }

        format += "{eventType},{timestampLocal},{configSlot},{pubIdTxt},{pvtIdTxt},{secretKeyTxt},{currentAccessCodeTxt},{newAccessCodeTxt},{oathFixedModhex1},{oathFixedModhex2},{oathFixedModhex},{hotpDigits},{oathMovingFactorSeed},{strongPw1},{strongPw2},{sendRef},{chalBtnTrig},{hmacLT64}";
    } else if(m_format == Format_Yubico) {
        format = "{serial},";
        if(ykConfig->programmingMode() == YubiKeyConfig::Mode_YubicoOtp) {
            format += "{pubIdTxt},{pvtIdTxt},";
        } else if(ykConfig->programmingMode() == YubiKeyConfig::Mode_OathHotp) {
            format += "{pubIdTxt},{oathMovingFactorSeed},";
        } else if(ykConfig->programmingMode() == YubiKeyConfig::Mode_ChalRespHmac) {
            format += ",0,";
        } else {
            format += ",,";
        }
        format += "{secretKeyTxt},{newAccessCodeTxt},{timestampFixed},";
    } else if(m_format == Format_Flexible) {
        format = m_flexibleFormat;
    } else {
        qDebug() << "unknown format" << m_format;
        return;
    }
    format = formatLog(ykConfig, format);
    out << format << endl;
    file->flush();
}
Пример #25
0
void GameBoard::Settings()
{
    QDialog *ajuste = new QDialog;


    QPushButton *mudar = new QPushButton("Mudar Parametros");

    connect(mudar, SIGNAL(clicked()), SLOT(change()));



    QLabel *texto = new QLabel;
    QLabel *title = new QLabel("<b><big>Atalhos</big></b>");

    QFile *config = new QFile("/home/vinicius/svn/unball/estrategia/visualization/Visualization Last Version/Visualization_last/Tabela.txt");//Colocar o diretório ao qual se encontra o arquivo Tabela.txt

    if(!config->open(QFile::ReadOnly | QFile::Text))
    {
        return;
    }
    QTextStream mOut(config);
    QString mTexto = mOut.readAll();

    texto->setText(mTexto);



    QVBoxLayout *lay =new QVBoxLayout;
    lay->addWidget(title);
    lay->addWidget(texto);
    lay->addWidget(mudar);

    ajuste->setLayout(lay);
    config->flush();
    mOut.flush();
    config->close();



    ajuste->show();

}
Пример #26
0
void DiskUtil::appendToLogFile(const QString &fileName, const QString &line) {

    static QDate today = QDate::currentDate();
    static QMap<QString, QFile *> openFiles;

    if (today != QDate::currentDate()) {
        for (QFile *file : openFiles) {
            file->close();
            delete file;
        }
        openFiles.clear();
        today = QDate::currentDate();
    }

    QFile *file;
    if (openFiles.contains(fileName)) {
        file = openFiles[fileName];
    } else {
        QString dirPath = logDir() + "/" + today.toString("yyyyMMdd");
        if (!QDir(dirPath).exists() && !QDir(logDir()).mkpath(today.toString("yyyyMMdd"))) {
            LogUtil::setLoggingEnabled(false);
            LogUtil::logError("Could not create log directory: %1\n"
                              "Logging system disabled.", dirPath);
            return;
        }

        QString path = dirPath + "/" + fileName;
        file = new QFile(path);
        if (!file->open(QIODevice::WriteOnly | QIODevice::Append)) {
            LogUtil::setLoggingEnabled(false);
            LogUtil::logError("Could not open log file: %1\n"
                              "Logging system disabled.", path);
            return;
        }

        openFiles[fileName] = file;
    }

    file->write(QString(QTime::currentTime().toString("HH:mm:ss.zzz ") + line + "\n").toUtf8());
    file->flush();
}
Пример #27
0
/*!
 *\~english
 *	Writes line in log with name \a log_name
 *\~russian
 *	Пишет строку в лог с именем \a log_name
 *\~
 *	\param log_name - \~english logfile name \~russian Путь к логу (не обязательно) \~
*/
void
aTests::printline2log(const QString &log_name)
{
	QString toWrite;
	toWrite.fill('=',60);
	toWrite+="\n";
	QFile f;
	if(log_name==QString::null)
	{
		f.open( QIODevice::WriteOnly, stdout );
		f.writeBlock((const char*)toWrite,strlen((const char*)toWrite));
	}
	else
	{
		f.setName(log_name);
		f.open( QIODevice::WriteOnly | QIODevice::Append );
		f.writeBlock((const char*)toWrite,strlen((const char*)toWrite));
		f.flush();
	}
	f.close();
}
Пример #28
0
//----------------------------------------------------------------------------------------------------------------------
void myMessageOutput(QtMsgType /*type*/, const QMessageLogContext& /*context*/, const QString& msg)
{
#ifdef TEST_ONLY
    static QFile logFile("TokenTest_Log.txt");
#else
    static QFile logFile("TokenGraver_Log.txt");
#endif

    if (!logFile.isOpen()) {
        logFile.open(QIODevice::Append);
        QString newStartString("\r\n\r\n==========================================\r\n   Новый запуск   ");
        newStartString += curDateTime() + "\r\n==========================================\r\n\r\n";
        logFile.write(newStartString.toLocal8Bit());
    }

    if(!msg.isEmpty()) {
        QString logMsg = curTime() + "   " + msg + "\r\n";
        logFile.write(logMsg.toLocal8Bit());
        logFile.flush();
    }
}
Пример #29
0
// 打开日志文件 log.txt,如果不是当天创建的,则使用创建日期把其重命名为 yyyy-MM-dd.log,并重新创建一个 log.txt
void LogHandlerPrivate::openAndBackupLogFile() {
    // 总体逻辑:
    // 1. 程序启动时 logFile 为 NULL,初始化 logFile,有可能是同一天打开已经存在的 logFile,所以使用 Append 模式
    // 2. logFileCreatedDate is null, 说明日志文件在程序开始时不存在,所以记录下创建时间
    // 3. 程序运行时检查如果 logFile 的创建日期和当前日期不相等,则使用它的创建日期重命名,然后再生成一个新的 log.txt 文件
    makeSureLogDirectory(); // 如果日志所在目录不存在,则创建
    QString logPath = logDir.absoluteFilePath("log.txt"); // 日志的路径
    // [[1]] 程序启动时 logFile 为 NULL
    if (NULL == logFile) {
        logFile = new QFile(logPath);
        logOut  = (logFile->open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Append)) ?  new QTextStream(logFile) : NULL;

        if (NULL != logOut) {
            logOut->setCodec("UTF-8");
        }

        // [[2]] 如果文件是第一次创建,则创建日期是无效的,把其设置为当前日期
        if (logFileCreatedDate.isNull()) {
            logFileCreatedDate = QDate::currentDate();
        }
        // TODO: 可以检查日志文件超过 30 个,删除 30 天前的日志文件
    }
    // [[3]] 程序运行时如果创建日期不是当前日期,则使用创建日期重命名,并生成一个新的 log.txt
    if (logFileCreatedDate != QDate::currentDate()) {
        logFile->flush();
        logFile->close();
        delete logOut;
        delete logFile;
        QString newLogPath = logDir.absoluteFilePath(logFileCreatedDate.toString("yyyy-MM-dd.log"));;
        QFile::copy(logPath, newLogPath); // Bug: 按理说 rename 会更合适,但是 rename 时最后一个文件总是显示不出来,需要 killall Finder 后才出现
        QFile::remove(logPath); // 删除重新创建,改变创建时间
        logFile = new QFile(logPath);
        logOut  = (logFile->open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Truncate)) ?  new QTextStream(logFile) : NULL;
        logFileCreatedDate = QDate::currentDate();

        if (NULL != logOut) {
            logOut->setCodec("UTF-8");
        }
    }
}
Пример #30
0
void DecodeAudioFile::WriteWavHeadToFile(QFile &f,int outLen, int sampleRate, int sampleSize, int channel)
{
    WAVFMT wavHeader ;
    wavHeader.RIFF[0] = 'R';
    wavHeader.RIFF[1] = 'I';
    wavHeader.RIFF[2] = 'F';
    wavHeader.RIFF[3] = 'F';

    wavHeader.totalSize = 44 + outLen;

    wavHeader.WAVE[0] = 'W';
    wavHeader.WAVE[1] = 'A';
    wavHeader.WAVE[2] = 'V';
    wavHeader.WAVE[3] = 'E';

    wavHeader.FMT[0] = 'f';
    wavHeader.FMT[1] = 'm';
    wavHeader.FMT[2] = 't';
    wavHeader.FMT[3] = ' ';

    wavHeader.FILTER = 0x00000010;
    wavHeader.formatTag = 1;
    wavHeader.channels = channel;
    wavHeader.sampleRate = sampleRate;
    wavHeader.bytesPerSec = sampleRate*sampleSize*channel/8;
    wavHeader.bytesInSample = sampleSize/8;
    wavHeader.bitsDepth = sampleSize;

    wavHeader.DATA[0] = 'd';
    wavHeader.DATA[1] = 'a';
    wavHeader.DATA[2] = 't';
    wavHeader.DATA[3] = 'a';

    wavHeader.dataSize = outLen;
    int pos = f.pos();
    f.seek(0);
    f.write((char*)&wavHeader,sizeof(WAVFMT));
    f.seek(pos);
    f.flush();
}