Last 52 lines are not written in csv file using qt - c++

I have one csv file in which 3 column and 866300 lines. I have try to write this data into other csv file. when i try to write it has write 866248 lines in file after that remaining 52 lines are not write in file. what is the problem I do not understand it. I have try to debug this problem using print that data on console then it has print till last line on the console. only the problem in write the data in file.
#include <QCoreApplication>
#include <QFile>
#include <QStringList>
#include <QDebug>
#include <QTextStream>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QFile file("C:/Users/hello/Downloads/hello.csv");
QFile write("new_data.csv");
if(!file.open(QIODevice::ReadOnly | QIODevice::Text))
{
qDebug()<<file.errorString();
return 1;
}
if(!write.open(QIODevice::WriteOnly |QIODevice::Append))
{
qDebug()<<file.errorString();
return 1;
}
QTextStream out(&write);
QStringList data;
while (!file.atEnd())
{
QString line = file.readLine();
data = line.split(',');
if (data[0]=="v1")
{
out<<line;
continue;
}
else
{
int seq = (data[0].toInt())-1;
QString str = QString::number(seq)+","+data[1]+","+data[2].trimmed();
qDebug()<<str;
out<<str<<"\n";
}
}
return a.exec();
}
please help.

Please close the file before the return a.exec(); this line and after the while loop. add this line below line.
write.close();

Related

Qt4 QSettings read array with multiple values

I have an .ini file of this form:
#init file:
[files]
fileAmount=2
file1=string1, string2, 0
file2=string1, string2, 1
//cpp file:
settings=new QSettings(QString(":resources/configuration"), QSettings::IniFormat);
int n=set("files/fileAmount").toInt();
for(int i=1; i<=n; i++){
QStringList list=settings->value("files/file"+QString::number(i)).toStringList();
out<<list[0]<<" "<<list[1]<<" "<<list[2]<<endl;
}
//output:
string1 string2 0
string1 string2 1
Is there any way to set whitespaces as delimiter for QStringList instead of komma?
i.e have this file:
#init file:
[files]
fileAmount=2
file1=string1 string2 0
file2=string1 string2 1
and get the same output?
Ini File:
C:\Users\username\AppData\Roaming\MyOrg\MyApp.ini
[files]
file1=string1 string2 0
Sample code for space delimited stringlist in ini file:
#include <QCoreApplication>
#include <QStringList>
#include <QSettings>
#include <QDebug>
void readSettings();
void writeSettings();
QStringList list;
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QSettings::setDefaultFormat(QSettings::IniFormat);
qApp->setApplicationName("MyApp");
qApp->setOrganizationName("MyOrg");
readSettings();
qDebug() << list;
writeSettings();
return a.exec();
}
void readSettings()
{
// read a space delimited value from QSettings string
// into a stringlist
QSettings s;
s.beginGroup("files");
QString temp = s.value("file1","string1 string2 0").toString();
list << temp.split(" ");
s.endGroup();
}
void writeSettings()
{
// write a space delimited value from QStringList
QSettings s;
s.beginGroup("files");
s.setValue("file1",list.join(" "));
s.endGroup();
}
Output:
("string1", "string2", "0")
Hope that helps.

Checking if root element exist in Xml using qt c++

I have an Xml file:
<?xml version="1.0" encoding="utf-8" ?>
<AppConfig>
<DefaultCulture></DefaultCulture>
<StartupMessageTitle></StartupMessageTitle>
<StartupMessageText></StartupMessageText>
<StartupMessageIcon>Information</StartupMessageIcon>
<DefaultProfileSettings>
<DriverName>wia</DriverName>
<UseNativeUI>false</UseNativeUI>
<IconID>0</IconID>
<MaxQuality>false</MaxQuality>
<AfterScanScale>OneToOne</AfterScanScale>
<Brightness>0</Brightness>
<Contrast>0</Contrast>
<BitDepth>C24Bit</BitDepth>
<PageAlign>Left</PageAlign>
<PageSize>Letter</PageSize>
<Resolution>Dpi100</Resolution>
<PaperSource>Glass</PaperSource>
</DefaultProfileSettings>
<!--
<AutoSaveSettings>
<FilePath></FilePath>
<ClearImagesAfterSaving>false</ClearImagesAfterSaving>
<Separator>FilePerPage</Separator>
</AutoSaveSettings>
-->
</AppConfig>
I need to check if root elements "AutoSaveSettings" exists in xml using qt c++ . if the root elements exists then remove the commented line before and after the Auto save settings? How can we do it in qt c++. How do I perform this operation in c++.Check if exists start element or root element
#include <QtCore>
#include <QtXml/QDomDocument>
#include <QDebug>
#include <QFile>
#include <QXmlStreamReader>
bool elementExists(const QFile &file, const QString &elementName)
{
QXmlStreamReader reader(&file);
while (reader.readNextStartElement())
{
if(reader.name() == elementName)
{
return true;
}
}
return false;
}
int main(int argc,char *argv[])
{
QCoreApplication a(argc,argv);
QDomDocument document;
QFile file = "C:/Program Files (x86)/NAPS2/appsettings.xml";
if(!file.open(QIODevice::ReadOnly | QIODevice::Text))
{
qDebug()<<"Failed to open the file";
return -1;
}
else{
if(!document.setContent(&file))
{
qDebug()<< "Failed to load Document";
return -1;
}
file.close();
}
elementExists(file,"AutoSaveSettings");
qDebug()<< "Finished";
return a.exec();
}
Try something like this :
bool elementExists( QFile & file, const QString & elementName){
QXmlStreamReader reader (&file);
while (reader.readNextStartElement()){
if(reader.name() == elementName) return true;
//elementName should be "AutoSaveSettings"
}
return false;
}
Edit : an alternative way could be using QDomDocument
Not recomanded because QDomDocument is not actively maintained anymore
bool elementExists( QFile & file,const QString & elementName){
QDomDocument reader;
reader.setContent(&file, true);
QDomNodeList elementList = reader.elementsByTagName(elementName);
return elementList.size()>0;
}

ASSERT: "allArguments.size() == origArgc"

I'm having this error in my Qt Application:
Debug Error!
Program: C:\Qt\Qt5.1.1\5.1.1\msvc2012_64\bin\QtCored.dll
Module: 5.1.1 File: global\qglobal.cpp
Line: 2014
ASSERT: "allArguments.size() == origArgc" in file
kernel\qcoreapplication.cpp, line 2095
#include <QCoreApplication>
#include <QDebug>
#include <QStringList>
int main(int argc, char *argv[])
{
QCoreApplication app(argc,argv);
qDebug()<<"argc:" << argc;
qDebug()<<"arguments:"<<app.arguments().length();
return 0;
}
Why is that so?
The issue was that I was passing arguments with a new line character in it.
After I removed, it worked again.

Cannot read lines in a file using boost filesystem

I have a cpp file which contains of:
#include <QApplication>
int/**/ main(int /*c*/,char**v)
{/*
*/
QApplication app(c,v);//
//
return app.exec();
/**/
}
I'm opening this file:
boost::filesystem3::path file("C:\\Users\\Art\\Desktop\\six_lines.txt");
boost::filesystem3::ifstream fin(file);
if (fin)
{
std::string read_line;
while (getline(fin,read_line))//here I'd hope to read just one line
{
}
}
Unfortunately getline(fin,read_line) is executed just once (file exists). Why?

Obtaining command line arguments in a Qt application

The following snippet is from a little app I wrote using the Qt framework. The idea is that the app can be run in batch mode (i.e. called by a script) or can be run interactively.
It is important therefore, that I am able to parse command line arguments in order to know which mode in which to run etc.
[Edit]
I am debugging using Qt Creator 1.3.1 on Ubuntu Karmic. The arguments are passed in the normal way (i.e. by adding them via the 'Project' settings in the Qt Creator IDE).
When I run the app, it appears that the arguments are not being passed to the application. The code below, is a snippet of my main() function.
int main(int argc, char *argv[])
{
//Q_INIT_RESOURCE(application);
try {
QApplication the_app(argc, argv);
//trying to get the arguments into a list
QStringList cmdline_args = QCoreApplication::arguments();
// Code continues ...
}
catch (const MyCustomException &e) { return 1; }
return 0;
}
[Update]
I have identified the problem - for some reason, although argc is correct, the elements of argv are empty strings.
I put this little code snippet to print out the argv items - and was horrified to see that they were all empty.
for (int i=0; i< argc; i++){
std::string s(argv[i]); //required so I can see the damn variable in the debugger
std::cout << s << std::endl;
}
Does anyone know how I can retrieve the command line args in my application?
If your argc and argv are good, I'm surprised this would be possible as QApplication::arguments() is extremely simple. Note the source code. Filtering the #ifdefs for Linux, it's just:
QStringList QCoreApplication::arguments()
{
QStringList list;
if (!self) {
qWarning("QCoreApplication::arguments: Please instantiate the QApplication object first");
return list;
}
const int ac = self->d_func()->argc;
char ** const av = self->d_func()->argv;
for (int a = 0; a < ac; ++a) {
list << QString::fromLocal8Bit(av[a]);
}
return list;
}
That's all you've got. There's a Unicode caveat which I would not think would apply to Karmic:
"On Unix, this list is built from the argc and argv parameters passed to the constructor in the main() function. The string-data in argv is interpreted using QString::fromLocal8Bit(); hence it is not possible to pass, for example, Japanese command line arguments on a system that runs in a Latin1 locale. Most modern Unix systems do not have this limitation, as they are Unicode-based."
You might try a copy of that code against your argc and argv directly and see what happens.
Only in order to keep response up-to-date, Qt now provides a dedicated class for parsing command line:
http://doc.qt.io/qt-5/qcommandlineparser.html
P.S. : can only post this as response and not a comment; I'm sorry because the question was not really how to parse but how to access.
If you are writing a Console only application then you might want to consider using QCoreApplication instead of QApplicition. QCoreApplication is part of QtCore while QApplication is defined in QtGui, so you get an extra and unnecessary dependency.
here is a simple example to have the arguments in a QStringList. Assuming you start the app with argument -q -t
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
QString x;
for (int i=1; i<argc; i++)
{
x.append(argv[i]);
}
qDebug() << x;
QStringList args = x.split("-");
args.removeFirst();
qDebug() << "args="<< args;
return a.exec();
}
Output is as follow
x= "-q-t"
args= ("q", "t")
Now you have the arguments as a QStringList ..
and here is a complete code i wrote and use in a small application
#include "mainwindow.h"
#include <QApplication>
#include <QDebug>
static QStringList arguments;
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
//analyze the arguments
//-b: use buidin player and if it does not exist use mpg123 shell to play files
//
//-t: test the player upon startup and exit
//-s: use the following speaker ID for the test
//-f: use the following file name and path
//syntax: example:
// -b : to use build in player
// -t -s xx:xx:xx:xx:xx -f azanfile.mp3: to test upon startup playing a file
bool useBuildInPlayer;
QString x;
for (int i=1; i<argc; i++)
{
x.append(argv[i]);
}
arguments << x.split("-"); arguments.removeFirst();
qDebug() << arguments;
if (arguments.indexOf("b")>=0)
useBuildInPlayer=true;
else
useBuildInPlayer=false;
bool TestSpeaker = false;
bool spkr=false; QString speaker;
bool playfile=false; QStringList testfiles;
QString filestring;
foreach (QString x, arguments)
{
if (x.left(1)=="s")
{
speaker = x.mid(1,-1); //remove the s from the beginning
spkr=true;
}
if (x.left(1)=="f")
{
filestring=x.mid(1,-1);
playfile=true;
testfiles<<filestring;
}
if (x=="t")
TestSpeaker = true;
}
if (TestSpeaker)
{
if (spkr)
{
qDebug() << "testing speaker "<< speaker;
}
else
{
qDebug() << "test argument needs speaker -s xx:xx:xx:xx:xx";
}
if (playfile)
{
qDebug() << "testing file "<< filestring;
}
else
{
qDebug() << "test file is missing";
}
}
if (TestSpeaker && spkr && playfile)
{
if (useBuildInPlayer) //use build in player
{
qDebug() << "testing using buildin player";
}
else // use mpg123 shell
{
qDebug() << "testing using mpg123 shell";
}
}
return a.exec();
}