Add string into a text file at a certain string value - c++

void elfenliedtopfan5_wep_adder_res::zonefilesetup(QString file)
{
QFile inputFile(file);
if (inputFile.open(QIODevice::ReadOnly))
{
QTextStream in(&inputFile);
while (!in.atEnd())
{
QString line = in.readLine();
if(line.contains("scriptparsetree,scripts/zm/" + elfenliedtopfan5settings->value("ModName").toString() + ".csc"))
{
qDebug() << "We Hit" << line;
break;
}
else
{
qDebug() << "We Did Not Hit" << line;
}
}
inputFile.close();
}
}
and what i wanting to do is add text under the line we hit so once found add text to file under that line
the file contents are
class,zm_mod_level
group,modtools
xmodel,skybox_default_day
material,luts_t7_default
// BSP
col_map,maps/zm/zm_elfenlied_v2.d3dbsp
gfx_map,maps/zm/zm_elfenlied_v2.d3dbsp
// Audio
sound,zm_elfenlied_v2
scriptparsetree,scripts/zm/zm_elfenlied_v2.gsc
scriptparsetree,scripts/zm/zm_elfenlied_v2.csc
// JARIK ELFENLIED LUA SETUP
scriptparsetree,scripts/zm/_zm_elfen_test.csc
scriptparsetree,scripts/zm/_zm_elfen_test.gsc
rawfile,ui/uieditor/menus/hud/T7Hud_zm_custom.lua
rawfile,ui/uieditor/widgets/elfenlied/zmElfenliedAmmoContainer.lua
rawfile,ui/uieditor/widgets/elfenlied/zmElfenLiedDefaultAmmo.lua
rawfile,ui/uieditor/widgets/elfenlied/zmElfenliedSpecialAmmo.lua
rawfile,ui/uieditor/widgets/elfenlied/zmElfenliedAmmoClipContainer.lua
rawfile,ui/uieditor/widgets/elfenlied/zmElfenliedGrenades.lua
image,elfenlied_special_ammo_stock_box
image,elfenlied_special_ammo_box
image,elfenlied_special_zombies_left_box
image,elfenlied_special_ammo_stock_box_red
image,elfenlied_special_ammo_box_red
image,elfenlied_special_zombies_left_box_red
image,elfenlied_anime_girl
image,gun_backing_main
// END
// ELFENLIED WEAPON HUDS.
image,uie_elfenlied_icon_p90_iw8_upg
image,uie_elfenlied_icon_pistol_standard
//ELFENLIEDTOPFAN5 MW19 PORTS
//MYSTERY BOX
stringtable,gamedata/weapons/zm/zm_levelcommon_weapons.csv
//WEAPONS
weapon,renetti
weapon,p90_iw8
weapon,p90_iw8_upg
//END
weapon,bo4_gks
weapon,bo4_gks_upgraded
weapon,aug_t8
weapon,aug_t8_upg
weapon,mp7_iw8
weapon,mp7_iw8_upg
the line i have found is
scriptparsetree,scripts/zm/zm_elfenlied_v2.csc
so want to find this line and under this line add more values but unsure how to accomplish this.
but unsure how to add strings under the line,
so once it finds that line
line in question found stript blablabla
// under this line in the file I want to add certain things but unsure how to approach this.

Related

How to write contents into a file in multiple steps?

I have a basic question:
I opened an old log file in the readonly mode and stored content in QTextStream, and closed it. It basically contains 7 lines of texts.
I opened another file to write and tried to read line by line. I can read line by line and write entire content into the new file. But I'm trying to do the follwoing:
Write first 5 lines as it is to the new file
do some change to Line 6 and 7 and write to the new line
QString oldfilename = "log_file";
QString newfilename = "new_log_file";
QString path1 = QCoreApplication::applicationDirPath()+"/"+oldfilename +".txt";
QString path2 = QCoreApplication::applicationDirPath()+"/"+newfilename+".txt";
QFile readfile(path1);
if(!readfile.open(QIODevice::ReadOnly | QIODevice::Text)){
qDebug() << "Error opening file: "<<readfile.errorString();
}
QTextStream instream(& readfile);
QFile writefile(path2);
if(file.open(QIODevice::WriteOnly | QIODevice::Text))
{
int nb_line(0);
while(!instream.atEnd())
{
QString line = instream.readLine();
// Here I need to write first five lines of the file as it is
if(nb_line == 6 )
{
// Do some manipulation here
outstream <line_6<< '\n'
}
if(nb_line == 7 )
{
// Do some manipulation here
outstream <line_7<< '\n'
}
++nb_line;
}
readfile.close();
writefile.close();
}
Can some one suggest an efficient way (using loops) to select first lines as it is and to manage changes to line 6 and 7
I can write whole contents line by line into the new file but not sure how to use right loops to select
for example if the contents of the old file is
Apple
Cherry
Pineapple
Pear
Grape
Mushroom
Egg
I need my new file as:
Apple
Cherry
Pineapple
Pear
Grape
Orange
Watermelone
since it is 5 lines you could write a simple while loop (I am using the fstream library)
void readFirstFiveLines() {
std::ifstream file("file.txt");
std::ofstream file2("file2.txt");
std::string line;
int i = 0;
while (std::getline(file, line) && i < 5) {
file2 << line << std::endl;
i++;
}
}

how to read only one line in a text file which has particular word using Qt

I am reading a .txt file, I want to read only 1 line with particular word. I'm using Qt Creator.
How can I achieve this?
This is my code so far:
QFile file("/home/a1.txt");
if (!file.open(QFile::ReadOnly | QFile::Text)) {
QMessageBox::warning(this,"title","file not open");
}
QTextStream in(&file);
QString text = in.readAll();
ui->plainTextEdit->setPlainText(text);
file.close();
If you want to search all lines for a specific word you can do this
QFile file("/home/a1.txt");
if (!file.open(QFile::ReadOnly | QFile::Text)) {
QMessageBox::warning(this,"title","file not open");
}
QTextStream in(&file);
QString text;
while (!in.atEnd()) {
text = in.readLine();
if (text.contains(/*Search her for the word you want.*/))
break;
}
ui->plainTextEdit->setPlainText(text);
file.close();
So you loop through all lines. And in every line you check if the word exist. If yes you can stop searching and leave the loop.
I hope this helps!

QstringList to Qstring conversion issues

I am working on VS2015 with qt framework. In my source code, I have a function for printing in the GUI screen.
This function is called each time something needs to be printed.
It goes like this.
void Trial::Print_MessageBox(QString string)
{
ui.MessagesScreen->appendPlainText(string);
Cursor_Messagebox.movePosition(QTextCursor::End);
ui.MessagesScreen->setTextCursor(Cursor_Messagebox);
ui.MessagesScreen->ensureCursorVisible();
}
// Output in MessageBox
void Trial::Print_MessageBox(QFlags<QNetworkInterface::InterfaceFlag> flags)
{
QString str = QString("Flag %1").arg(flags);
ui.MessagesScreen->appendPlainText(str);
}
The above function has no problems and running well.
Now I am trying to read a text file. This has set of values in no order or size. An example for this:
231, 54, 4 \n
47777, 2211, 676, 9790, 34236, 7898\n
1, 3\n
Objective is to convert these into integers (line by line) and print them in the GUI and also send them (line by line) to other system. So I tried to do it with the following.
void Trial::ReadFile_Data()
{
QFile file("input.txt");
if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
{
Print_MessageBox("Error in reading File");
return;
}
QTextStream in(&file);
while (!in.atEnd())
{
QString line = in.readLine();
Print_MessageBox(line);
int conv = line.toInt();
QString str = QString("%1 %2").arg("Values are: ").arg(conv);
Print_MessageBox(str);
QStringList fields = line.split(",");
}
file.close();
}
When I print the "line", it is just printing the same values as in the file. When I do the conversion and printing, I get an error (which is expected) Now I try to remove "," with the help of split then I get QstringList which I cannot use as I have the Qstring function to print(this cant be changed)
I am not getting any pointers from here. Please help me out as this is bugging me since long time.
Just simple...
QStringList::const_iterator constIterator;
for (constIterator = fonts.constBegin(); constIterator != fonts.constEnd();
++constIterator) {
cout << (*constIterator).toLocal8Bit().constData() << endl;
}
where fonts is your QStringlist
Your question reduces to "How do I iterate over a QStringList".
Like this:
// C++11
for (auto field : fields) Print_messageBox(field);
// C++98
foreach (QString field, fields) Print_messageBox(field);
See here for information about how foreach a.k.a Q_FOREACH was implemented.

Qt delete a line from file

I am reading a QFile with QTextStream.
QFile file("example.txt");
QTextStream in(&file);
QString line = in.readLine();
while (!line.isNull()) {
if(line.contains("DELETE"))
{
// delete line
}
line = in.readLine();
}
Is there a way to delete a line ?
You can open your file, read the contents, modify the contents, and then write them back to the file. Here is one way to do this:
QFile f("myfile.txt");
if(f.open(QIODevice::ReadWrite | QIODevice::Text))
{
QString s;
QTextStream t(&f);
while(!t.atEnd())
{
QString line = t.readLine();
if(!line.contains("DELETE"))
s.append(line + "\n");
}
f.resize(0);
t << s;
f.close();
}
As far as i know, it's not simple as that. The best solution i can think about is to the read the whole file line-by-line, push every line into a QVector, then modify the container's elements as you want, then push it back to the file.
delete a line means shift of all the rest backward.
simplest way is to write back lines in new place after first deletion.
Using temp file, and rename it to the original if success, is the safest way.
but you never write more then you read so it suppose to be OK to work on the same file.
you need to keep read pos and write pos.
it should be something like this: (based on the original code)
QFile file("example.txt");
QTextStream in(&file,QIODevice::ReadWrite);
QString line = in.readLine();
qint64 rpos,wpos=0;
bool shift = false;
while (!line.isNull()) {
rpos = in.pos();
if(!line.contains("DELETE"))
{
if(shift){
in.seek(wpos);
in<<line<<endl;
wpos = in.pos();
in.seek(rpos);
} else{
wpos = rpos;
}
}else{
shift = true;
}
in.seek(rpos);
line = in.readLine();
}
file.resize(wpos);

change the name file putting the first line of my file C++ & Qt

I want to change the name of my file but I don't know how to do it. I have a .txt with words in two lines,and like to take the first line same as name of my file .txt.
This is my code:
void ventana1::on_ButtonGuardar_clicked()
{
QDir directory("C:/Users/Jaime/Desktop/interfaz/pacientes");
QString mFilename = directory.filePath("paciente.txt");
QFile sFile(mFilename);
if(sFile.open(QFile::WriteOnly | QFile::Text))
{
QTextStream out(&sFile);
out << ui.lineEdit_2->text()<< "\n"
<< ui.lineEdit->text();
sFile.flush();
sFile.close();
}
}
Simply replace
QString mFilename = directory.filePath("paciente.txt");
by
QString mFilename = directory.filePath(ui.lineEdit_2->text());
if you need to have the content of your lineEdit as your filename.