read a text file to QStringList - qt

I have a text file. I need to read it to a QStringList. there are no line seperators. I mean each line in the text file is in a new line. So is there anyway i can do this?

I assume that every line should be a separate string in the list. Use QTextStream::readLine() in a cycle and on each step append the returned value to the QStringList. Like this:
QStringList stringList;
QFile textFile;
//... (open the file for reading, etc.)
QTextStream textStream(&textFile);
while (true)
{
QString line = textStream.readLine();
if (line.isNull())
break;
else
stringList.append(line);
}

QFile TextFile;
//Open file for reading
QStringList SL;
while(!TextFile.atEnd())
SL.append(TextFile.readLine());

If the file isn't too big, read the whole content into a QString and then split() it into a QStringList.
I like using the QRegExp version to handle linefeed from different platforms:
QStringList sList = s.split(QRegExp("(\\r\\n)|(\\n\\r)|\\r|\\n"), QString::SkipEmptyParts);

I like my code to be fully indented/paranthesized with obvious variable names (they may take longer to type but are much easier to debug) so would do the following (but changing "myTextFile" and "myStringList" to more sensible names, such as "employeeListTextFile")
QFile myTextFile;
QStringList myStringList;
if (!myTextFile.open(QIODevice::ReadOnly))
{
QMessageBox::information(0, "Error opening file", myTextFile.errorString());
}
else
{
while(!myTextFile.atEnd())
{
myStringList.append(myTextFile.readLine());
}
myTextFile.close();
}

The below code reads the file
QFile File("/file_path");
if(!File.open(QIODevice::ReadOnly));
{
qDebug("Error");
}
QTextStream in(&File);
while(!in.atEnd())
{
qDebug()<<ReadAll;
ReadAll=in.readAll();
}
File.close();
Now the file is closed, now split the new line i.e \n here \r is carriage return
List= ReadAll.split(QRegExp("[\r\n]"),QString::SkipEmptyParts);

Related

How to can append the value from txt file to the Qlist

How I can to insert the value from txt file in to the Qlist...
QList<QString> list_StRead;
list_StRead.insert();
I can sorting txt file ... its mean that my file is a line by line. than after the insert to the Qlist I want to write in to Qtabelewidget. How I must to do?? u must to be completely understand. see the img file
tnx for all....
Here is the pseudo code.
Please try it. (Not tested, code written in notepad. excuse me any syntax errors).
//Your list
QList<QString> list_StRead;
//Text stream object read data and insert in list.
QTextStream in(&file);
while (!in.atEnd())
{
QString line = in.readLine(); //read one line at a time
list_StRead.push_back(line);
}
//loop your list
for(int i =0; i<list_StRead.size(); i++)
{
//Add by create your tablewidget item and append it.
YourTableWidget->setItem(rowNumber,colNumber,new QTableWidgetItem(list_StRead.at(i)))
}

QFile: new file name append to tho last saved

I'm looking for the error I made on this code, but I can not find any solution since hours..
This function should simpli save a file to a directory:
void MyClass::saveSettingsToFile(QString file_name)
{
QString path;
path = dir.append(file_name);
QFile my_file(path);
if (!my_file.open(QFile::WriteOnly))
{
qDebug() << "Could not open file for writing";
}
QTextStream out(& my_file);
out << "some text \n"
my_file.flush();
my_file.close();
path = "";
file_name ="";
}
Where dir is a QString containing the directory, file_name is gathered from a lineEdit field.
When I first call the function with, for example file_name = "aaaa.txt", I find this aaaa.txt in the specified directory. All right.
When then I call again the function with file_name = "bbbb.txt", I find in the specified directory this file: aaaa.txtbbbb.txt, instead of I
bbbb.txt
It seems to me a very s****d error, but I cannot find what!
EDITED: there was this mistake QTextStream out(& path); instead of QTextStream out(& my_file);
You are modifying dir variable with QString::append. Variable dir is obviously a class member of MyClass. Try this instead:
void MyClass::saveSettingsToFile(QString file_name)
{
QString path(dir);
path.append(file_name);
QFile my_file(path);
//...
}
The QString::append function modify the parameter value itself as you can see in the documentation: http://doc.qt.io/qt-5/qstring.html#append
Example:
QString x = "free";
QString y = "dom";
x.append(y);
// x == "freedom"
So, what happens is that it keeps appending the content to the dir variable, not only assigning the result to path.

check if a file extension is part of a given list

I am trying to make a simple widget which contains a lineedit which shows the file name and a button to open a filedialog.
and now I want to check if the file-extension is valid, in this case, a image file ending with jpg, png or bmp. I solved this with QFileInfo and QList, this code is in my btn_clicked slot:
QString filename = QFileDialog::getOpenFileName(this, tr("Select an image File", "", tr("Image Files (*.bmp *.jpg *.png);; All Files(*)"));
QList<QString> ext_list;
ext_list<<"bmp"<<"jpg"<<"png";
QFileInfo fi(filename);
QString ext = fi.suffix();
if (ext_list.contains(ext)){
// lineedit->setText(filename);
}
else {
QMessageBox msgBox;
msgBox.critical(0, "Error", "You must select a valid image file");
it works, but is there a more simple/elegant way to achieve the goal? Thx for your help.
You might be interested by the setNameFilters function : http://doc.qt.io/qt-5/qfiledialog.html#setNameFilters
Update
If you want to filter images without naming each extensions, you should use QMimeDatabase. This will allow you to define your filter for the QFileDialog and then get a list of extensions to check.
For example with jpeg and png:
QStringList mimeTypeFilters;
mimeTypeFilters << "image/jpeg" << "image/png";
QFileDialog fd;
fd.setFileMode(QFileDialog::ExistingFile);
fd.setMimeTypeFilters(mimeTypeFilters);
fd.exec();
QString filename = fd.selectedFiles().count() == 1 ? fd.selectedFiles().at(0) : "";
QMimeDatabase mimedb;
if(!mimeTypeFilters.contains(mimedb.mimeTypeForFile(filename).name()))
{
// something is wrong here !
}

Finding a specific character in a file in Qt

How can i find a specific character in a QFile which has a text in it?
for example i have ' $5000 ' written somewhere in my file. in want to find the "$" sign so i will realize that I've reached the number.
I tried using QString QTextStream::read(qint64 maxlen) by putting 1 as the maxlen :
QFile myfile("myfile.txt");
myfile.open(QIODevice::ReadWrite | QIODevice::Text);
QTextStream myfile_stream(&myfile);
while(! myfile_stream.atEnd())
{
if( myfile_stream.read(1) == '$')
{
qDebug()<<"found";
break;
}
}
and i get "error: invalid conversion from 'char' to 'const char* "
i also tried using the operator[] but apparently it can't be used for files.
Read in a line at a time and search the text that you've read in
QTextStream stream(&myFile);
QString line;
do
{
line = stream.readLine();
if(line.contains("$"))
{
qDebug()<<"found";
break;
}
} while (!line.isNull());
The error message you've posted doesn't match the issue in your code. Possibly the error was caused by something else.
QTextStream::read returns QString. You can't compare QString and const char* directly, but operator[] can help:
QString s = stream.read(1);
if (s.count() == 1) {
if (s[0] == '$') {
//...
}
}
However reading a file by too small pieces will be very slow. If your file is small enough, you can read it all at once:
QString s = stream.readAll();
int index = s.indexOf('$');
If your file is large, it's better to read file by small chunks (1024 bytes for example) and calculate the index of found character using indexOf result and count of already read chunks.
a single char could be read with
QTextStream myfile_stream(&myfile);
QChar c;
while (!myfile_stream.atEnd())
myfile_stream >> c;
if (c == '$') {
...
}
myfile_stream.read(1) - this is not good practice, you should not read from file one byte at a time. Either read the entire file, or buffered/line by line if there is a risk for the file to be too big to fit in memory.
The error you get is because you compare a QString for equality with a character literal - needless to say that is not going to work as expected. A string is a string even if there is only one character in it. As advised - use either the [] operator or better off for reading - QString::at() const which is guaranteed to create no extra copy. You don't use it on the QFile, nor on the QTextStream, but on the QString that is returned from the read() method of the text stream targeted at the file.
Once you have the text in memory, you can either use the regular QString methods like indexOf() to search for the index of a contained character.
in want to find the "$" sign so i will realize that I've reached the
number.
It sounds to me that you're searching for the '$' symbol because you're more interested in the dollar value that follows it. In this case, I suggest reading the files line by line and running them through a QRegExp to extract any values you're looking for.
QRegExp dollarFind("\\$(\\d+)");
while(!myfile_stream.atEnd()){
QString line = myfile_stream.readLine();
if (dollarFind.exactMatch(line)){
QStringList dollars = dollarFind.capturedTexts();
qDebug() << "Dollar values found: " << dollars.join(", ");
}
}

How to make a QString from a QTextStream?

Will this work?
QString bozo;
QFile filevar("sometextfile.txt");
QTextStream in(&filevar);
while(!in.atEnd()) {
QString line = in.readLine();
bozo = bozo + line;
}
filevar.close();
Will bozo be the entirety of sometextfile.txt?
Why even read line by line? You could optimize it a little more and reduce unnecessary re-allocations of the string as you add lines to it:
QFile file(fileName);
if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) return;
QTextStream in(&file);
QString text;
text = in.readAll();
file.close();
As ddriver mentions, you should first open the file using file.open(…); Other than that, yes bozo will contain the entirety of the file using the code you have.
One thing to note in ddriver's code is that text.reserve(file.size()); is unnecessary because on the following line:
text = in.readAll();
This will replace text with a new string so the call to text.reserve(file.size()); would have just done unused work.

Resources