本文整理汇总了C++中QFile类的典型用法代码示例。如果您正苦于以下问题:C++ QFile类的具体用法?C++ QFile怎么用?C++ QFile使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了QFile类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: aDir
void ProcessesList::produzirListaProcessos(){
this->listaProcessos.clear();
QDir *directory;
QFile *arquivo;
QString *S;
QStringList files;
std::string data;
QDir aDir("/proc");
aDir.setFilter(QDir::Dirs);
QStringList entries = aDir.entryList();
this->numThreads = 0;
for( QStringList::ConstIterator entry=entries.begin(); entry!=entries.end(); ++entry)
{
S = new QString("/proc/" + QString(*entry));
if((S->compare("/proc/.") == 0) || (S->compare("/proc/..") == 0)){
continue;
}
directory = new QDir(*S);
if(!directory->exists()){
continue;
} else if(!((S->toStdString()[6] >= '0') && (S->toStdString()[6] <= '9'))){
continue;
}
directory->setFilter(QDir::Files);
arquivo = new QFile(*S + "/status");
if((!arquivo)){
qDebug() << "ERRO 1! (" << *S << ")";
continue;
} else if(!arquivo->open(QIODevice::ReadOnly | QIODevice::Text)){
qDebug() << arquivo->errorString();
qDebug() << "ERRO 2! (" << *S << ")";
continue;
}
process P;
QTextStream buffer(arquivo);
QStringList fileContent = buffer.readAll().split("\n");
QString buf;
P.nome = processName(fileContent.at(0));
P.status = processStatus(fileContent.at(1));
P.pid = processPid(fileContent.at(3));
P.ppid = processPPid(fileContent.at(4));
P.user = processUser(fileContent.at(6));
for (int var = 7; var < fileContent.size(); ++var) {
buf = fileContent.at(var);
if(buf.startsWith("Threads")){
break;
}
}
P.threads = processThreadsNumber(buf);
this->numThreads += P.threads;
P.trocas_contexto = processTrocasContexto(fileContent.at(fileContent.size()-3),fileContent.at(fileContent.size()-2));
this->listaProcessos.push_back(P);
arquivo->close();
}
delete arquivo;
delete directory;
delete S;
}
示例2: Calcuration
/**
* 計算およびDB構築
*
* @param[in] n サンプル数
*/
void RMAThread::Calcuration(int n)
{
// 変数宣言
QString readFileName; // 読み込みファイル名
QFile readFile; // 読み込みファイル
QString readFileLine; // 読み込みファイル行
QString writeFileName; // 書き込みファイル名
QFile writeFile; // 書き込みファイル
vector <PliceData> pliceData; // 時系列データ
double ma_open; // MA(Open)
double ma_high; // MA(High)
double ma_low; // MA(Low)
double ma_close; // MA(Close)
double ma_volume; // MA(Volume)
double ma_aClose; // MA(AClose)
double pMa_open; // 前日のMA(Open)
double pMa_high; // 前日のMA(High)
double pMa_low; // 前日のMA(Low)
double pMa_close; // 前日のMA(Close)
double pMa_volume; // 前日のMA(Volume)
double pMa_aClose; // 前日のMA(AClose)
PliceData tempData; // 一時保存用時系列データ
QString temp_1; // 一時保存用文字列
QString temp_2; // 一時保存用文字列
// ディレクトリ生成
_mkdir("DB\\RMA_" + temp_1.setNum(n).toLocal8Bit());
// 各IDについて処理実行
for (int i = 1000; i < 1000000; i++) {
if (((i > 10000) && !((i == 998405) || (i == 998407)))) {
continue;
}
// 変数初期化
pliceData.clear();
// 読み込み用ファイルオープン
readFileName = "Yahoo\\" + temp_1.setNum(i) + ".csv";
readFile.setFileName(readFileName);
if (readFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
// 宣言&初期化
QTextStream readFileReader(&readFile);
readFileLine = "";
// 時系列データの読み取り
while (!readFileReader.atEnd()) {
readFileLine = readFileReader.readLine();
// データ取得
if (readFileLine != "") {
tempData.mDate = QDate::fromString((readFileLine.split(",").at(0)), "yyyy/M/d");
tempData.mOpen = readFileLine.split(",").at(1).toDouble();
tempData.mHigh = readFileLine.split(",").at(2).toDouble();
tempData.mLow = readFileLine.split(",").at(3).toDouble();
tempData.mClose = readFileLine.split(",").at(4).toDouble();
tempData.mVolume = readFileLine.split(",").at(5).toDouble();
tempData.mAClose = readFileLine.split(",").at(6).toDouble();
pliceData.push_back(tempData);
}
}
// 書き込み用ファイルオープン
writeFileName = "DB\\RMA_" + temp_1.setNum(n) + "\\" + temp_2.setNum(i) + ".dat";
writeFile.setFileName(writeFileName);
if (!writeFile.open(QIODevice::WriteOnly | QIODevice::Text)) {
return;
}
// 書き込み処理
for (int j = n; j < (int)pliceData.size(); j++) {
QTextStream out(&writeFile);
// RMA計算
ma_open = 0;
ma_high = 0;
ma_low = 0;
ma_close = 0;
ma_volume = 0;
ma_aClose = 0;
if (j == n) {
for (int k = 0; k < n; k++) {
ma_open += pliceData[j-k].mOpen;
ma_high += pliceData[j-k].mHigh;
ma_low += pliceData[j-k].mLow;
ma_close += pliceData[j-k].mClose;
ma_volume += pliceData[j-k].mVolume;
ma_aClose += pliceData[j-k].mAClose;
}
ma_open = ma_open / n;
ma_high = ma_high / n;
ma_low = ma_low / n;
ma_close = ma_close / n;
ma_volume = ma_volume / n;
ma_aClose = ma_aClose / n;
}
//.........这里部分代码省略.........
示例3: parseCueFile
int CueSheetModel::parseCueFile(QFile &cueFile, const QDir &baseDir, QCoreApplication *application, const QTextCodec *codec)
{
cueFile.reset();
qDebug("\n[Cue Sheet Import]");
bool bForceLatin1 = false;
//Reject very large files, as parsing might take until forever
if(cueFile.size() >= 10485760i64)
{
qWarning("File is very big. Probably not a Cue Sheet. Rejecting...");
return 2;
}
//Test selected Codepage for decoding errors
qDebug("Character encoding is: %s.", codec->name().constData());
const QString replacementSymbol = QString(QChar(QChar::ReplacementCharacter));
QByteArray testData = cueFile.peek(1048576);
if((!testData.isEmpty()) && codec->toUnicode(testData.constData(), testData.size()).contains(replacementSymbol))
{
qWarning("Decoding error using selected codepage (%s). Enforcing Latin-1.", codec->name().constData());
bForceLatin1 = true;
}
testData.clear();
//Init text stream
QTextStream cueStream(&cueFile);
cueStream.setAutoDetectUnicode(false);
cueStream.setCodec(bForceLatin1 ? "latin1" : codec->name());
cueStream.seek(0i64);
//Create regular expressions
QRegExp rxFile("^FILE\\s+(\"[^\"]+\"|\\S+)\\s+(\\w+)$", Qt::CaseInsensitive);
QRegExp rxTrack("^TRACK\\s+(\\d+)\\s(\\w+)$", Qt::CaseInsensitive);
QRegExp rxIndex("^INDEX\\s+(\\d+)\\s+([0-9:]+)$", Qt::CaseInsensitive);
QRegExp rxTitle("^TITLE\\s+(\"[^\"]+\"|\\S+)$", Qt::CaseInsensitive);
QRegExp rxPerformer("^PERFORMER\\s+(\"[^\"]+\"|\\S+)$", Qt::CaseInsensitive);
QRegExp rxGenre("^REM\\s+GENRE\\s+(\"[^\"]+\"|\\S+)$", Qt::CaseInsensitive);
QRegExp rxYear("^REM\\s+DATE\\s+(\\d+)$", Qt::CaseInsensitive);
bool bPreamble = true;
bool bUnsupportedTrack = false;
CueSheetFile *currentFile = NULL;
CueSheetTrack *currentTrack = NULL;
m_albumTitle.clear();
m_albumPerformer.clear();
m_albumGenre.clear();
m_albumYear = 0;
//Loop over the Cue Sheet until all lines were processed
for(int lines = 0; lines < INT_MAX; lines++)
{
if(application)
{
application->processEvents();
if(lines < 128) Sleep(10);
}
if(cueStream.atEnd())
{
qDebug("End of Cue Sheet file.");
break;
}
QString line = cueStream.readLine().trimmed();
/* --- FILE --- */
if(rxFile.indexIn(line) >= 0)
{
qDebug("%03d File: <%s> <%s>", lines, rxFile.cap(1).toUtf8().constData(), rxFile.cap(2).toUtf8().constData());
if(currentFile)
{
if(currentTrack)
{
if(currentTrack->isValid())
{
currentFile->addTrack(currentTrack);
currentTrack = NULL;
}
else
{
LAMEXP_DELETE(currentTrack);
}
}
if(currentFile->isValid())
{
m_files.append(currentFile);
currentFile = NULL;
}
else
{
LAMEXP_DELETE(currentFile);
}
}
else
{
LAMEXP_DELETE(currentTrack);
}
if(!rxFile.cap(2).compare("WAVE", Qt::CaseInsensitive) || !rxFile.cap(2).compare("MP3", Qt::CaseInsensitive) || !rxFile.cap(2).compare("AIFF", Qt::CaseInsensitive))
//.........这里部分代码省略.........
示例4: QVERIFY2
void HuggleTest::testCaseScores()
{
Huggle::Configuration::HuggleConfiguration->LocalConfig_ScoreWords.clear();
Huggle::Configuration::HuggleConfiguration->LocalConfig_ScoreWords.append(new Huggle::ScoreWord("fuck", 10));
Huggle::Configuration::HuggleConfiguration->LocalConfig_ScoreWords.append(new Huggle::ScoreWord("fucking", 20));
Huggle::Configuration::HuggleConfiguration->LocalConfig_ScoreWords.append(new Huggle::ScoreWord("vagina", 50));
Huggle::Configuration::HuggleConfiguration->LocalConfig_ScoreWords.append(new Huggle::ScoreWord("fuck this bitch", 20));
Huggle::Configuration::HuggleConfiguration->LocalConfig_ScoreWords.append(new Huggle::ScoreWord("suck", 60));
Huggle::Configuration::HuggleConfiguration->LocalConfig_ScoreWords.append(new Huggle::ScoreWord("ass", 60));
Huggle::Configuration::HuggleConfiguration->SystemConfig_WordSeparators << " " << "." << "," << "(" << ")" << ":" << ";" << "!" << "?" << "/";
Huggle::GC::gc = new Huggle::GC();
Huggle::WikiEdit *edit = new Huggle::WikiEdit();
edit->Page = new Huggle::WikiPage("test");
edit->User = new Huggle::WikiUser("Harry, the vandal");
edit->DiffText = "fuck this vagina!";
edit->Score = 0;
edit->ProcessWords();
QVERIFY2(edit->Score == 60, QString("01 Invalid result for score words: " + QString::number(edit->Score)).toUtf8().data());
QVERIFY2(edit->ScoreWords.contains("vagina"), "02 Invalid result for score words");
QVERIFY2(edit->ScoreWords.contains("fuck"), "03 Invalud result for score words");
edit->DiffText = "fuc_k vagina!";
edit->Score = 0;
edit->ProcessWords();
QVERIFY2(edit->Score == 50, QString("04 Invalid result for score words: " + QString::number(edit->Score)).toUtf8().data());
QVERIFY2(edit->ScoreWords.contains("vagina"), "05 Invalid result for score words");
edit->DiffText = "Hey bob, (fuck) there is some vagina.";
edit->Score = 0;
edit->ProcessWords();
QVERIFY2(edit->Score == 60, "06 Invalid result for score words");
QVERIFY2(edit->ScoreWords.contains("vagina"), "07 Invalid result for score words");
QVERIFY2(edit->ScoreWords.contains("fuck"), "08 Invalid result for score words");
edit->DiffText = "Hey bob, fuck this bitch over.";
edit->Score = 0;
edit->ProcessWords();
QVERIFY2(edit->Score == 30, "06 Invalid result for score words");
edit->DiffText = "Hey bob, (fuck) there is some vagina, let's fuck that vagina.";
edit->Score = 0;
edit->ProcessWords();
QVERIFY2(edit->Score == 60, QString("09 Invalid result for score words: " + QString::number(edit->Score)).toUtf8().data());
QVERIFY2(edit->ScoreWords.contains("vagina"), "10 Invalid result for score words");
QVERIFY2(edit->ScoreWords.contains("fuck"), "12 Invalid result for score words");
edit->DiffText = "Hey bob, there are vaginas over there";
edit->Score = 0;
edit->ProcessWords();
QVERIFY2(edit->Score == 0, QString("14 Invalid result for score words: " + QString::number(edit->Score)).toUtf8().data());
edit->DiffText = "Hey bob, mind if I'd be fucking with you?";
edit->Score = 0;
edit->ProcessWords();
QVERIFY2(edit->Score == 20, QString("16 Invalid result for score words: " + QString::number(edit->Score)).toUtf8().data());
edit->DiffText = "Hey bob, stop fuckin that vagina!!";
edit->Score = 0;
edit->ProcessWords();
QVERIFY2(edit->Score == 50, QString("18 Invalid result for score words: " + QString::number(edit->Score)).toUtf8().data());
QFile *vf = new QFile(":/test/wikipage/page01.txt");
vf->open(QIODevice::ReadOnly);
edit->DiffText = QString(vf->readAll());
edit->Score = 0;
edit->ProcessWords();
delete vf;
QVERIFY2(edit->Score == 0, QString("20 Invalid result for score words: " + QString::number(edit->Score)).toUtf8().data());
vf = new QFile(":/test/wikipage/page02.txt");
vf->open(QIODevice::ReadOnly);
edit->DiffText = QString(vf->readAll());
edit->Score = 0;
edit->ProcessWords();
delete vf;
QVERIFY2(edit->Score == 0, QString("22 Invalid result for score words: " + QString::number(edit->Score)).toUtf8().data());
vf = new QFile(":/test/wikipage/page03.txt");
vf->open(QIODevice::ReadOnly);
edit->DiffText = QString(vf->readAll());
edit->Score = 0;
edit->ProcessWords();
delete vf;
QVERIFY2(edit->Score == 60, QString("26 Invalid result for score words: " + QString::number(edit->Score)).toUtf8().data());
vf = new QFile(":/test/wikipage/page04.txt");
vf->open(QIODevice::ReadOnly);
edit->DiffText = QString(vf->readAll());
edit->Score = 0;
edit->ProcessWords();
delete vf;
QVERIFY2(edit->Score == 10, QString("26 Invalid result for score words: " + QString::number(edit->Score)).toUtf8().data());
edit->SafeDelete();
delete Huggle::GC::gc;
Huggle::GC::gc = NULL;
}
示例5: createJsonStandard
//.........这里部分代码省略.........
}
ejecutablesCat.append(ejeCat);
ambitCat.insert("Ejecutables",ejecutablesCat);
//Crear QJsonObject ambitEsp
ambitEsp.insert("Nombreambito",QJsonValue(QString("Espanya 5 metres")));
if(_objectSettingPref->existPathImageEspSett())
{
ambitEsp.insert("Path",_objectSettingPref->getSettingImageEsp());
}
else
{
ambitEsp.insert("Path",QJsonValue(QString("//Pedros/Disc_E/Antonio/mosaicMetEspanya.rf")));
}
ambitEsp.insert("TamanyoPixel",QJsonValue(int(5)));
ambitEsp.insert("Utm",QJsonValue(int(30)));
ejeEsp.insert("Nombre",QJsonValue(QString("exeFootPrintMask")));
if(_objectSettingPref->existExeFootPSett())
{ ejeEsp.insert("Path",_objectSettingPref->getExeFootPrintMask());}
else
{ejeEsp.insert("Path",QJsonValue(QString("//nas03/geoproces/dfapplications/ICCImageOperations/exe/ICCImageFootPrintMask.exe")));
}
ejecutablesEsp.append(ejeEsp);
ejeEsp.insert("Nombre",QJsonValue(QString("exeResize")));
if(_objectSettingPref->existExeResiSett())
{ ejeEsp.insert("Path",_objectSettingPref->getExeResize());}
else
{ejeEsp.insert("Path",QJsonValue(QString("//empuries/PRODUCCIO/DFApplications/ICCImageOperations/exe/ICCImageresize.exe")));
}
ejecutablesEsp.append(ejeEsp);
ejeEsp.insert("Nombre",QJsonValue(QString("exeSubScene")));
if(_objectSettingPref->existExeSubeSett())
{ ejeEsp.insert("Path",_objectSettingPref->getExeSubScene());}
else
{ ejeEsp.insert("Path",QJsonValue(QString("//nas03/geoproces/dfapplications/ICCImageOperations/exe/ICCImageSubescenes.exe")));
}
ejecutablesEsp.append(ejeEsp);
ejeEsp.insert("Nombre",QJsonValue(QString("exeGeoTransform")));
if(_objectSettingPref->existExeImaOpeoSett())
{ejeEsp.insert("Path",_objectSettingPref->getExeImaOpeGeo());}
else
{ejeEsp.insert("Path",QJsonValue(QString("//nas03/geoproces/DFApplications/ICCImageOperationsGeoCorrection/exe/ICCImageGeoTransformation.exe")));
}
ejecutablesEsp.append(ejeEsp);
ambitEsp.insert("Ejecutables",ejecutablesEsp);
//Crear QJsonObject ambitFran
ambitFran.insert("Nombreambito",QJsonValue(QString("Francia Farmstar")));
if(_objectSettingPref->existPathImageFraSett())
{ ambitFran.insert("Path",_objectSettingPref->getSettingImageFran());}
else
{ ambitFran.insert("Path",QJsonValue(QString("//Pedros/Disc_E/Antonio/MosaicMetFarmstar_NTF_ELIP.rf")));}
ambitFran.insert("TamanyoPixel",QJsonValue(int(10)));
ambitFran.insert("Utm",QJsonValue(int(-2)));
ejeFran.insert("Nombre",QJsonValue(QString("exeFootPrintMask")));
if(_objectSettingPref->existExeFootPSett())
{ejeFran.insert("Path",_objectSettingPref->getExeFootPrintMask());}
else
{ ejeFran.insert("Path",QJsonValue(QString("//nas03/geoproces/dfapplications/ICCImageOperations/exe/ICCImageFootPrintMask.exe")));
}
ejecutablesFran.append(ejeFran);
ejeFran.insert("Nombre",QJsonValue(QString("exeResize")));
if(_objectSettingPref->existExeResiSett())
{ejeFran.insert("Path",_objectSettingPref->getExeResize());}
else
{ ejeFran.insert("Path",QJsonValue(QString("//empuries/PRODUCCIO/DFApplications/ICCImageOperations/exe/ICCImageresize.exe")));
}
ejecutablesFran.append(ejeFran);
ejeFran.insert("Nombre",QJsonValue(QString("exeSubScene")));
if(_objectSettingPref->existExeSubeSett())
{ ejeFran.insert("Path",_objectSettingPref->getExeSubScene());}
else
{ ejeFran.insert("Path",QJsonValue(QString("//nas03/geoproces/dfapplications/ICCImageOperations/exe/ICCImageSubescenes.exe")));
}
ejecutablesFran.append(ejeFran);
ejeFran.insert("Nombre",QJsonValue(QString("exeResize")));
if(_objectSettingPref->existExeResiSett())
{ejeFran.insert("Path",_objectSettingPref->getExeResize());}
else
{ejeFran.insert("Path",QJsonValue(QString("//empuries/PRODUCCIO/DFApplications/ICCImageOperations/exe/ICCImageresize.exe")));
}
ejecutablesFran.append(ejeFran);
ambitFran.insert("Ejecutables",ejecutablesFran);
QJsonArray array;
array.prepend((ambitCat));
array.prepend((ambitFran));
array.prepend((ambitEsp));
QJsonDocument documento;
documento.setArray(array);
QFile documentoTexto;
QTextStream value;
QString PathFileJsonDefecto=qApp->applicationDirPath()+"/dataAplicationToolsPcot.txt";
documentoTexto.setFileName(PathFileJsonDefecto);
documentoTexto.open(QFile::WriteOnly | QFile::Text);
value.setDevice(&documentoTexto);
value << documento.toJson();
}
示例6: currentFile
//----------------------------------------------------------------------
// Silently save ride and convert to GC format without warning user
//----------------------------------------------------------------------
void
MainWindow::saveSilent(RideItem *rideItem)
{
QFile currentFile(rideItem->path + QDir::separator() + rideItem->fileName);
QFileInfo currentFI(currentFile);
QString currentType = currentFI.completeSuffix().toUpper();
QFile savedFile;
bool convert;
// Do we need to convert the file type?
if (currentType != "JSON") convert = true;
else convert = false;
// Has the date/time changed?
QDateTime ridedatetime = rideItem->ride()->startTime();
QChar zero = QLatin1Char ( '0' );
QString targetnosuffix = QString ( "%1_%2_%3_%4_%5_%6" )
.arg ( ridedatetime.date().year(), 4, 10, zero )
.arg ( ridedatetime.date().month(), 2, 10, zero )
.arg ( ridedatetime.date().day(), 2, 10, zero )
.arg ( ridedatetime.time().hour(), 2, 10, zero )
.arg ( ridedatetime.time().minute(), 2, 10, zero )
.arg ( ridedatetime.time().second(), 2, 10, zero );
// if there is a notes file we need to rename it (cpi we will ignore)
QFile notesFile(currentFI.path() + QDir::separator() + currentFI.baseName() + ".notes");
if (notesFile.exists()) notesFile.remove();
// When datetime changes we need to update
// the filename & rename/delete old file
// we also need to preserve the notes file
if (currentFI.baseName() != targetnosuffix) {
// rename as backup current if converting, or just delete it if its already .gc
// unlink previous .bak if it is already there
if (convert) {
QFile::remove(currentFile.fileName()+".bak"); // ignore errors if not there
currentFile.rename(currentFile.fileName(), currentFile.fileName() + ".bak");
} else currentFile.remove();
convert = false; // we just did it already!
// set the new filename & Start time everywhere
currentFile.setFileName(rideItem->path + QDir::separator() + targetnosuffix + ".json");
rideItem->setFileName(QFileInfo(currentFile).path(), QFileInfo(currentFile).fileName());
}
// set target filename
if (convert) {
// rename the source
savedFile.setFileName(currentFI.path() + QDir::separator() + currentFI.baseName() + ".json");
} else {
savedFile.setFileName(currentFile.fileName());
}
// update the change history
QString log = rideItem->ride()->getTag("Change History", "");
log += tr("Changes on ");
log += QDateTime::currentDateTime().toString() + ":";
log += '\n' + rideItem->ride()->command->changeLog();
rideItem->ride()->setTag("Change History", log);
// save in GC format
JsonFileReader reader;
reader.writeRideFile(this, rideItem->ride(), savedFile);
// rename the file and update the rideItem list to reflect the change
if (convert) {
// rename on disk
QFile::remove(currentFile.fileName()+".bak"); // ignore errors if not there
currentFile.rename(currentFile.fileName(), currentFile.fileName() + ".bak");
// rename in memory
rideItem->setFileName(QFileInfo(savedFile).path(), QFileInfo(savedFile).fileName());
}
// mark clean as we have now saved the data
rideItem->ride()->emitSaved();
}
示例7: QNetworkAccessManager
#if 1
if ((longitude != std::numeric_limits<double>::infinity()) && (latitude != std::numeric_limits<double>::infinity())) {
network_manager = new QNetworkAccessManager();
QObject::connect(network_manager,SIGNAL(finished(QNetworkReply*)),this,SLOT(dataReceived(QNetworkReply*)));
network_manager->get(QNetworkRequest(QUrl("http://api.yr.no/weatherapi/locationforecast/1.9/?lat=" + QString::number(latitude,'f',2) + ";lon=" + QString::number(longitude,'f',2))));
fetch_timer = new QTimer();
QObject::connect(fetch_timer,SIGNAL(timeout()),this,SLOT(fetchAgain()));
}
#else
/******** Dummy ***********/
QDomDocument doc;
QFile f(QStringLiteral("c:/temp/api.yr.no.xml"));
f.open(QIODevice::ReadOnly);
doc.setContent(f.readAll());
f.close();
qDebug() << "constr onXML";
onXMLReceived(doc.documentElement());
/******** End Dummy ***********/
#endif
}
void QVWeather::dataReceived(QNetworkReply* reply) {
if (reply->isRunning()) {
return;
}
示例8: parseTag
bool KNMusicTagWav::parseTag(QFile &musicFile,
QDataStream &musicDataStream,
KNMusicAnalysisItem &analysisItem)
{
//Check file size.
if(musicFile.size()<12)
{
//It cannot be a wav format file, until a valid one.
return false;
}
//Gernerate the header cache.
char rawHeader[12];
//Read the header.
musicDataStream.readRawData(rawHeader, 12);
//Check the riff header and the wave header.
if(memcmp(rawHeader, m_riffHeader, 4)!=0 ||
memcmp(rawHeader+8, m_waveHeader, 4)!=0)
{
//This is not a wav file.
return false;
}
/*
* WAV file is a combination of several chunks.
* Read all the chunks, and find LIST and id32 chunk.
*/
//Get the music file size.
qint64 fileSize=musicFile.size();
//Generate the chunk header cache.
char chunkHeader[8];
//Initial the chunk found flag.
bool listFound=false, id32Found=false;
//We have to prepare the list here and write the data after parse all the
//data, we want the id32 chunk has a higher priority than list chunk.
//Prepare the wav item list for list chunk.
QList<WAVItem> listData;
//Generate the raw frame linked list for id32 chunk.
QLinkedList<ID3v2Frame> frames;
//Generate the id3v2 frame function set for id32 chunk.
ID3v2FunctionSet functionSet;
//Start finding the chunk.
while(musicDataStream.device()->pos()<fileSize && !listFound && !id32Found)
{
//Read chunk head.
musicDataStream.readRawData(chunkHeader, 8);
//Calculate the chunk size.
quint32 chunkSize=KNMusicUtil::inverseCharToInt32(chunkHeader+4);
//Check if it's list chunk
if(memcmp(chunkHeader, m_listChunk, 4)==0)
{
//Set list chunk found flag to true.
listFound=true;
//Generate chunk size cache.
char *listRawData=new char[chunkSize];
//Read the raw data.
musicDataStream.readRawData(listRawData, chunkSize);
//Parse list chunk.
parseListChunk(listRawData, chunkSize, listData);
//Recover memory.
delete[] listRawData;
}
//Check if it's id32 chunk.
else if(memcmp(chunkHeader, m_id32Chunk, 4)==0)
{
//Generate ID3v2 header cache.
char rawHeader[10];
//Generate ID3v2 header structure.
ID3v2Header header;
//Read ID3v2 header data.
musicDataStream.readRawData(rawHeader, 10);
//Parse the ID3v2 header.
//and then Check is chunk size smaller than tag size.
if(!parseID3v2Header(rawHeader, header) ||
chunkSize<(header.size+10))
{
//If we cannot parse it, skip the whole chunk.
musicDataStream.skipRawData(chunkSize-10);
//Continue to next chunk.
continue;
}
//Generate the raw tag data field.
char *rawTagData=new char[header.size];
//Read the raw tag data.
musicDataStream.readRawData(rawTagData, header.size);
//Get the function set according to the minor version of the header.
getId3v2FunctionSet(header.major, functionSet);
//Parse the raw data.
parseID3v2RawData(rawTagData, header, functionSet, frames);
//Recover the memory.
delete[] rawTagData;
//Set the id32 chunk find flag to true.
id32Found=true;
}
//For all the other chunks.
else
{
//Skip the data.
musicDataStream.skipRawData(chunkSize);
}
}
//Check if the list data is not empty, first.
//.........这里部分代码省略.........
示例9: QFileToifstream
std::ifstream QFileToifstream(QFile & file) {
Q_ASSERT(file.isReadable());
return std::ifstream(::_fdopen(file.handle(), "r"));
}
示例10: QDir
void cProfileSettings::save ()
{
cProfileManager *pm = cProfileManager::self();
QString path = pm->profilePath (d->profileId);
QDir dir = QDir (path);
if (!dir.exists()) QDir::root().mkpath (dir.absolutePath());
dir.remove ("settings.backup");
if (!QFile(path + "/settings.xml").copy (path + "/settings.backup")) {
kDebug() << "Unable to backup settings.xml." << endl; // not fatal, may simply not exist
}
QFile f (path + "/settings.xml");
if (!f.open(QIODevice::WriteOnly | QIODevice::Truncate | QIODevice::Text)) {
kDebug() << "Unable to open settings.xml for writing." << endl;
return; // problem
}
// save the profile file
QXmlStreamWriter *writer = new QXmlStreamWriter (&f);
writer->setAutoFormatting (true); // make the generated XML more readable
writer->writeStartDocument ();
writer->writeStartElement ("profile");
writer->writeAttribute ("version", "1.0");
// boolean values
map<QString, bool>::iterator itb;
for (itb = d->boolVals.begin(); itb != d->boolVals.end(); ++itb) {
writer->writeStartElement ("setting");
writer->writeAttribute ("type", "bool");
writer->writeAttribute ("name", itb->first);
writer->writeAttribute ("value", itb->second ? "true" : "false");
writer->writeEndElement ();
}
// integer values
map<QString, int>::iterator it;
for (it = d->intVals.begin(); it != d->intVals.end(); ++it) {
writer->writeStartElement ("setting");
writer->writeAttribute ("type", "integer");
writer->writeAttribute ("name", it->first);
writer->writeAttribute ("value", QString::number (it->second));
writer->writeEndElement ();
}
// string values
map<QString, QString>::iterator it2;
for (it2 = d->strVals.begin(); it2 != d->strVals.end(); ++it2) {
writer->writeStartElement ("setting");
writer->writeAttribute ("type", "string");
writer->writeAttribute ("name", it2->first);
writer->writeAttribute ("value", it2->second);
writer->writeEndElement ();
}
writer->writeEndElement ();
writer->writeEndDocument ();
f.close ();
delete writer;
}
示例11: isRelative
/*!
\overload
Sets the file that the QFileInfo provides information about to \a
file.
If \a file includes a relative path, the QFileInfo will also have
a relative path.
\sa isRelative()
*/
void QFileInfo::setFile(const QFile &file)
{
setFile(file.fileName());
}
示例12: parseVICESnapshot
qint64 StateImport::parseVICESnapshot(QFile& file, quint8* buffer64k)
{
struct VICESnapshotHeader header;
struct VICESnapshoptModule module;
struct VICESnapshoptC64Mem c64mem;
static const char VICE_MAGIC[] = "VICE Snapshot File\032";
static const char VICE_C64MEM[] = "C64MEM";
auto state = State::getInstance();
if (!file.isOpen())
file.open(QIODevice::ReadOnly);
auto size = file.size();
if (size < (qint64)sizeof(VICESnapshotHeader))
{
state->setErrorMessage(QObject::tr("Error: VICE file too small"));
return -1;
}
file.seek(0);
size = file.read((char*)&header, sizeof(header));
if (size != sizeof(header))
{
state->setErrorMessage(QObject::tr("Error: VICE header too small"));
return -1;
}
if (memcmp(header.id, VICE_MAGIC, sizeof(header.id)) != 0)
{
state->setErrorMessage(QObject::tr("Error: Invalid VICE header Id"));
return -1;
}
int offset = file.pos();
bool found = false;
while (1) {
size = file.read((char*)&module, sizeof(module));
if (size != sizeof(module))
break;
/* Found? */
if (memcmp(module.moduleName, VICE_C64MEM, sizeof(VICE_C64MEM)) == 0 &&
module.major == 0)
{
found = true;
break;
}
offset += qFromLittleEndian(module.lenght);
if (!file.seek(offset))
break;
}
if (found)
{
size = file.read((char*)&c64mem, sizeof(c64mem));
if (size != sizeof(c64mem))
{
state->setErrorMessage(QObject::tr("Error: Invalid VICE C64MEM segment"));
return -1;
}
memcpy(buffer64k, c64mem.ram, sizeof(c64mem.ram));
}
else
{
state->setErrorMessage(QObject::tr("Error: VICE C64MEM segment not found"));
return -1;
}
return 0;
}
示例13: property
int TorrentPlugin::AddJob (Entity e)
{
QString suggestedFname;
if (e.Entity_.canConvert<QUrl> ())
{
QUrl resource = e.Entity_.toUrl ();
if (resource.scheme () == "magnet")
{
QString at = XmlSettingsManager::Instance ()->
property ("AutomaticTags").toString ();
QStringList tags = e.Additional_ [" Tags"].toStringList ();
Q_FOREACH (QString tag, Core::Instance ()->GetProxy ()->
GetTagsManager ()->Split (at))
tags << Core::Instance ()->GetProxy ()->
GetTagsManager ()->GetID (tag);
QList<QPair<QString, QString> > queryItems = resource.queryItems ();
for (QList<QPair<QString, QString> >::const_iterator i = queryItems.begin (),
end = queryItems.end (); i != end; ++i)
if (i->first == "kt")
{
QStringList humanReadable = i->second
.split ('+', QString::SkipEmptyParts);
Q_FOREACH (QString hr, humanReadable)
tags += Core::Instance ()->GetProxy ()->
GetTagsManager ()->GetID (hr);
}
return Core::Instance ()->AddMagnet (resource.toString (),
e.Location_,
tags,
e.Parameters_);
}
else if (resource.scheme () == "file")
suggestedFname = resource.toLocalFile ();
}
QByteArray entity = e.Entity_.toByteArray ();
QFile file (suggestedFname);
if ((!file.exists () ||
!file.open (QIODevice::ReadOnly)) &&
Core::Instance ()->IsValidTorrent (entity))
{
QTemporaryFile file ("lctemporarybittorrentfile.XXXXXX");
if (!file.open ())
return -1;
file.write (entity);
suggestedFname = file.fileName ().toUtf8 ();
file.setAutoRemove (false);
}
AddTorrentDialog_->Reinit ();
AddTorrentDialog_->SetFilename (suggestedFname);
if (!e.Location_.isEmpty ())
AddTorrentDialog_->SetSavePath (e.Location_);
QString path;
QStringList tags = e.Additional_ [" Tags"].toStringList ();
QVector<bool> files;
QString fname;
bool tryLive = e.Additional_ ["TryToStreamLive"].toBool ();
if (e.Parameters_ & FromUserInitiated)
{
if (!tags.isEmpty ())
AddTorrentDialog_->SetTags (tags);
if (AddTorrentDialog_->exec () == QDialog::Rejected)
return -1;
fname = AddTorrentDialog_->GetFilename (),
path = AddTorrentDialog_->GetSavePath ();
tryLive = AddTorrentDialog_->GetTryLive ();
files = AddTorrentDialog_->GetSelectedFiles ();
tags = AddTorrentDialog_->GetTags ();
if (AddTorrentDialog_->GetAddType () == Core::Started)
e.Parameters_ &= ~NoAutostart;
else
e.Parameters_ |= NoAutostart;
}
else
{
fname = suggestedFname;
path = e.Location_;
QString at = XmlSettingsManager::Instance ()->
property ("AutomaticTags").toString ();
Q_FOREACH (QString tag, Core::Instance ()->GetProxy ()->
GetTagsManager ()->Split (at))
tags << Core::Instance ()->GetProxy ()->
GetTagsManager ()->GetID (tag);
}
int result = Core::Instance ()->AddFile (fname,
path,
tags,
tryLive,
files,
e.Parameters_);
setActionsEnabled ();
file.remove ();
//.........这里部分代码省略.........
示例14: QObject
ClientSocketOpt::ClientSocketOpt(QObject *parent) : QObject(parent)
{
timerid = -1;
recvCounts = 0;
socket = nullptr;
socketThread = new QThread;
socketThread->setObjectName("client socket thread");
this->moveToThread(socketThread);
connect(socketThread, &QThread::finished, this, [=] () {
this->deleteLater();
socketThread->deleteLater();
});
connect(this, &ClientSocketOpt::connectHost,
this, [=] (QString ip, quint16 port) {
socket = new QTcpSocket(this);
connect(socket, &QTcpSocket::connected,
this, [=] () {
// connected
emit connected();
});
socket->connectToHost(ip, port);
if (!socket->waitForConnected())
{
emit recvInformation(cn("接收终止"));
emit disconnected();
socketThread->quit();
return;
}
QFile *file = new QFile(this);
TcpDataDeal *deal = new TcpDataDeal(this);
MessageDataDeal *msg = new MessageDataDeal(this);
connect(deal, &TcpDataDeal::fullFrameData,
msg, &MessageDataDeal::ParserFrameData);
connect(msg, &MessageDataDeal::recvMessageData,
this, [=] (MessageData data) {
if (data.datatype() != FileSendType &&
data.datatype() != commonStr)
return;
if (data.datatype() == commonStr)
{
MessageCharData *charconent = dynamic_cast<MessageCharData*>(data.content());
if (charconent && charconent->type() == FileInfo)
{
QString strinfo = QString::fromLocal8Bit(charconent->content());
emit recvInformation(strinfo);
}
return;
}
// write file
FileDataContent *content = dynamic_cast<FileDataContent*>(data.content());
if (!content)
return;
FileDataContent::FileHead *head = content->sendInfo();
FileDataContent::FileNameHead *namehead = content->fileName();
emit recvProgress(head->totalProgress >= 100 ? 99 : head->totalProgress, head->currentProgress / 100.0);
QString filename = namehead->name.replace(namehead->path, savePath + "/");
QFileInfo info(filename);
emit recvInformation(cn("正在接收 %1").arg(info.fileName()));
QDir dir(info.absolutePath());
if (!dir.exists())
dir.mkpath(info.absolutePath());
if (file->fileName() != filename)
{
file->close();
if (info.exists())
{
QString dt = QDateTime::currentDateTime().toString("yyyyMMddhhmmss");
filename = info.absolutePath() + "/" +
info.bundleName() + dt + "." + info.suffix();
}
file->setFileName(filename);
}
if (!file->isOpen())
{
file->open(QIODevice::WriteOnly | QIODevice::Append);
}
if (file->isWritable())
{
file->write(content->data(), head->fileCurrentSize);
if (head->currentProgress == 100)
file->close();
}
if (socketThread->isInterruptionRequested())
{
emit recvInformation(cn("接收终止"));
file->close();
socket->disconnectFromHost();
socket->abort();
socketThread->quit();
}
if (head->currentProgress == 100 && head->totalProgress == 100)
{
file->close();
emit recvProgress(100, 1);
emit recvInformation(cn("接收完成"));
//.........这里部分代码省略.........
示例15: QFile
int XmlGspInterface::readFile(const QString &fileName)
{
QFile* file = new QFile(fileName);
QFileInfo fi(fileName);
QString path = (fi.path().length() > 3) ? QString(fi.path() + "/") : fi.path();
QFileInfo si(QString::fromStdString(_schemaName));
QString schemaPath(si.absolutePath() + "/");
if (!file->open(QIODevice::ReadOnly | QIODevice::Text))
{
std::cout << "XmlGspInterface::readFile() - Can't open xml-file " <<
fileName.toStdString() << "." << std::endl;
delete file;
return 0;
}
if (!checkHash(fileName))
{
delete file;
return 0;
}
QDomDocument doc("OGS-PROJECT-DOM");
doc.setContent(file);
QDomElement docElement = doc.documentElement(); //OpenGeoSysProject
if (docElement.nodeName().compare("OpenGeoSysProject"))
{
std::cout << "XmlGspInterface::readFile() - Unexpected XML root." << std::endl;
delete file;
return 0;
}
QDomNodeList fileList = docElement.childNodes();
for(int i = 0; i < fileList.count(); i++)
{
const QString file_node(fileList.at(i).nodeName());
if (file_node.compare("geo") == 0)
{
XmlGmlInterface gml(_project, schemaPath.toStdString() + "OpenGeoSysGLI.xsd");
const QDomNodeList childList = fileList.at(i).childNodes();
for(int j = 0; j < childList.count(); j++)
{
const QDomNode child_node (childList.at(j));
if (child_node.nodeName().compare("file") == 0)
{
std::cout << "path: " << path.toStdString() << "#" << std::endl;
std::cout << "file name: " << (child_node.toElement().text()).toStdString() << "#" << std::endl;
gml.readFile(QString(path + child_node.toElement().text()));
}
}
}
else if (file_node.compare("stn") == 0)
{
XmlStnInterface stn(_project, schemaPath.toStdString() + "OpenGeoSysSTN.xsd");
const QDomNodeList childList = fileList.at(i).childNodes();
for(int j = 0; j < childList.count(); j++)
if (childList.at(j).nodeName().compare("file") == 0)
stn.readFile(QString(path + childList.at(j).toElement().text()));
}
else if (file_node.compare("msh") == 0)
{
const std::string msh_name = path.toStdString() +
fileList.at(i).toElement().text().toStdString();
FileIO::MeshIO meshIO;
MeshLib::Mesh* msh = meshIO.loadMeshFromFile(msh_name);
_project->addMesh(msh);
}
}
return 1;
}