I'm trying to replace the text of a specific line, but got no success. (i'd searched a lot, but i don't found nothing)
something like:
hello
my
friend!
replacing line 2 to some text:
hello
AEEEHO NEW LINE TEXT
friend!
I created a QStringList and tried to read the text line by line and add to this list by changing just the line, but without success.
int line = 1; // to change the second line
QString newline = "my new text";
QStringList temp;
int i = 0;
foreach(QString curlineSTR, internalCode.split('\n'))
{
if(line == i)
temp << newline;
else
temp << curlineSTR;
i++;
}
internalCode = "";
foreach(QString txt, temp)
internalCode.append(QString("%1\n").arg(txt));
I belive that you are looking for QRegExp to deal with newline and do something like this:
QString internalcode = "hello\nmy\nfriend!";
int line = 1; // to change the second line
QString newline = "another text";
// Split by newline command
QStringList temp = internalcode.split(QRegExp("\n|\r\n|\r"));
internalcode.clear();
for (int i = 0; i < temp.size(); i++)
{
if (line == i)
internalcode.append(QString("%0\n").arg(newline));
else
internalcode.append(QString("%0\n").arg(temp.at(i)));
}
//Use this to remove the last newline command
internalcode = internalcode.trimmed();
qDebug() << internalcode;
And the output:
"hello
another text
friend!"
Related
I am storing some data in QDataStream and immediately taking the data, but the count is showing zero while retriving. code looks fine but unexpected behaviour
//Overloading
QDataStream& operator<< (QDataStream& writeTO, const CascadeJobInfo& data)
{
writeTO << data.m_infoJobType << data.m_connectionName << data.m_submitJobId << data.m_submitJobStat;
return writeTO;
}
QDataStream& operator>> (QDataStream& readIn, CascadeJobInfo& data)
{
readIn >> data.m_infoJobType >> data.m_connectionName >> data.m_submitJobId >> data.m_submitJobStat;
return readIn;
}
void Fun()
{
// Code Starts here
projectFileName = /*Path to folder*/
QFile file(projectFileName);
file.open(QFile::ReadWrite);
file.close();
QDataStream dStream(&file);
int jobLstCount = /*Get the Count, assume 4*/
dStream << jobLstCount;
for(int i = 0; i < jobLstCount; i++)
{
JobInfo.m_infoJobType = jobFlowItem->getJobType();
JobInfo.m_connectionName = submitItem->connectionName();
JobInfo.m_submitJobId = submitItem->jobID();
JobInfo.m_submitJobStat = submitItem->jobState();
// All valid data stored here
}
file.close();
QDataStream dStreamOut(&file);
dStreamOut >> jobLstCount; /*Count returns zero here insted of 4*/
CascadeJobInfo jobInfo;
// Why jobLstCount is getting zero here
for(int i = 0 ; i < jobLstCount ; i++)
{
dStreamOut >> jobInfo;
}
}
file.open(QFile::ReadWrite);
file.close(); <--- HERE
QDataStream dStream(&file);
You are closing the file as soon as you open it, so basically you are working with an invalid file descriptor which won't work. Put file.close() at the end of the code when you are done.
I am beginner in UI design using Qt. My project now is doing comparison. For example: if I have 2 text file.
How can I compare the number line by line? Because I have so many text file like this, and I need compare them on by one.What I can do now is only read the text file by line order. Thank you so much!
The procedure is simple
Read both files (always make sure they are opened successfully)
Read files line by line and convert strings to numbers for comparison.
Quit if there is no data left.
Moreover, you need to make sure that the format of files is consistent otherwise, you need to make sure what you manipulate is a real number. I assume numbers are integers but of course you can change it. Extra precautions are required in this kind of project. I will leave it to you. The simplified code for the above procedure is
#include <QString>
#include <QFile>
#include <QDebug>
#include <QTextStream>
int main()
{
QFile data1("text1.txt");
if (!data1.open(QIODevice::ReadOnly | QIODevice::Text)){
qDebug() << "text1.txt file can't be opened...";
return -1;
}
QFile data2("text2.txt");
if (!data2.open(QIODevice::ReadOnly | QIODevice::Text)){
qDebug() << "text2.txt file can't be opened...";
return -1;
}
QTextStream in1(&data1), in2(&data2);
while ( !in1.atEnd() && !in2.atEnd() ) {
QString num1 = in1.readLine();
QString num2 = in2.readLine();
if ( num1.toInt() > num2.toInt() )
qDebug() << num1.toInt() << ">" << num2.toInt();
// do the rest of comparison
}
return 0;
}
Now in my case, the txt files are
text1.txt
1
2
3
4
text2.txt
3
5
1
6
The output is
3 > 1
Edit: the OP is looking for the difference and its sum.
int sum(0);
while ( !in1.atEnd() && !in2.atEnd() ) {
QString num1 = in1.readLine();
QString num2 = in2.readLine();
int result = num1.toInt() - num2.toInt();
qDebug() << num1.toInt() << "-" << num2.toInt() << " = " << result;
sum += result;
}
qDebug() << "sum = " << sum;
Basic approach would be something like this:
QString filename1("C:/Users/UserName/Downloads/t1.txt");
QString filename2("C:/Users/UserName/Downloads/t2.txt");
QFile file(filename1);
file.open(QIODevice::ReadOnly);
QTextStream in(&file);
QStringList textOfFile1;
while (!in.atEnd()) {
QString line = in.readLine();
textOfFile1.append(line);
}
QFile file2(filename2);
file2.open(QIODevice::ReadOnly);
QTextStream in2(&file2);
QStringList textOfFile2;
while (!in.atEnd()) {
QString line = in.readLine();
textOfFile2.append(line);
}
if(textOfFile1.size() != textOfFile2) return false;
for(int i = 0; i < textOfFile1.size(); i++)
{
if(textOfFile1[i] != textOfFile2[i]) return false;
}
return true;
i.e. You read the files into a QStringList and you compare the lists line by line. This way you can also catch the firs # of line where there was a mismatch. Note that such comparison also considers white spaces such as \n \t etc.
PS: wrap the readers into functions, to avoid duplication like me. :)
Hope this helps ;)
I am trying to reconstruct an image from a file which is in Intel hex 386 format. After parsing the file all the data I am copying to a QByteArray and same array is used to create a QImage Object. But whatever image is which I got after reconstructing is not perfect. I am getting blue color instead of black, edges are not clear etc. The text file which I am parsing is a ram memory dump from STM32F4 controller (arm).The image is stored in RGB565 format.
Code to create the image:
{
QString strFilename;
Hex386Parser oFileParser;
strFilename = QFileDialog::getOpenFileName(this,"Select a file", QDir::homePath());
oFileParser.parseFile(strFilename, oByteArray);
QImage image(320, 240, QImage::Format_RGB16);
for (int y = 0; y < image.height(); y++)
{
memcpy(image.scanLine(y), oByteArray.constData() + y * image.bytesPerLine(),
image.bytesPerLine());
}
qDebug() <<"Size of the byte array is " <<oByteArray.size();
QLabel *label = new QLabel();
label->setPixmap(QPixmap::fromImage(image));
label->show();
}
Code to used to parse the file:
#define QT_NO_CAST_TO_ASCII
void Hex386Parser::parseFile(QString strFilename,QByteArray& ref_ByteArray)
{
QFile oFile(strFilename);
std::stringstream sstr;
QString strLength;
int unLength = 0, unAddress = 0,unDescriptor =0xFFFF,nIndex =0,nlineno=0;
if (oFile.open((QIODevice::ReadOnly | QIODevice::Text)))
{
QTextStream in(&oFile);
while (!in.atEnd())
{
QString line = in.readLine();
nIndex = 0;
nlineno++;
//unsigned char *pCharFrame = (unsigned char *)line.toStdString().c_str();
if (':' != line.at(nIndex))
{
// file corrupted
return;
}
nIndex++;
{
strLength = line.mid(nIndex, 2);
sstr << strLength.toStdString();
sstr << std::hex;
sstr >> unLength; // get length of the record
strLength.clear();
sstr.clear();
}
nIndex += 2;
unAddress = line.mid(nIndex,4).toInt(); // get address bytes
nIndex +=4;
unDescriptor = line.mid(nIndex, 2).toInt(); // get data descriptor
nIndex += 2;
switch(unDescriptor)
{
case data_record:
ref_ByteArray.append((line.mid(nIndex, unLength )));
// add data to bytearray
break;
case end_of_file_record:
break;
case extended_segment_address_record:
break;
case extended_linear_address_record:
break;
case start_linear_address_record:
break;
}
}
oFile.close();
}
}
What am I doing wrong??
The line contains hex string data representations where each byte is coded as two characters.
You want binary bytes. So, 2 * unLength symbols should be read from line. Then, that data string should converted to binary, for example:
{
case data_record:
QByteArray hex = line.mid(nIndex, 2 * unLength ).toLatin1();
QByteArray binary = QByteArray::fromHex(hex);
ref_ByteArray.append(binary);
...
}
I'm trying to parse a QString character by character with a while loop, but I can't figure out how to parse an individual character to char type. Here's my code, I know it's not optimal:
QString temp = (QString)t[0];
int i = 1;
while (t[i] != " ");
{
temp.append(t[i]);
i += 1;
}
I've seen the casting with toLocal8bit function, but whatever I try I just cannot adapt it to my code.
Qt Creator shows this error:
error: conversion from 'const char [2]' to 'QChar' is ambiguous
in line with the while function call
You can use C++ 11 range based for loop
for (auto chr : text)
{
if (!chr.isDigit()) // for exmpl.
return false;
}
Why don't you try that :
QString test = "test";
for(int i = 0; i< test.length(); i++)
{
if (test.at(i) != " ")
test.at(i).toLatin1();
}
I have a table view with three columns; I have just passed to write into text file using this code
QFile file("/home/hamad/lesson11.txt");
if(!file.open(QIODevice::WriteOnly)) {
QMessageBox::information(0,"error",file.errorString());
}
QString dd;
for(int row=0; row < model->rowCount(); row++) {
dd = model->item(row,0)->text() + ","
+ model->item(row,1)->text() + ","
+ model->item(row,2)->text();
QTextStream out(&file);
out << dd << endl;
}
But I'm not succeed to read the same file again, I tried this code but I don't know where is the problem in it
QFile file("/home/hamad/lesson11.txt");
QTextStream in(&file);
QString line = in.readLine();
while(!in.atEnd()) {
QStringList fields = line.split(",");
model->appendRow(fields);
}
Any help please ?
You have to replace string line
QString line = in.readLine();
into while:
QFile file("/home/hamad/lesson11.txt");
if(!file.open(QIODevice::ReadOnly)) {
QMessageBox::information(0, "error", file.errorString());
}
QTextStream in(&file);
while(!in.atEnd()) {
QString line = in.readLine();
QStringList fields = line.split(",");
model->appendRow(fields);
}
file.close();