Read text file in QStringList

I have a text file. I need to read it in a QStringList. no line dividers. I mean, each line in a text file is in a new line. Anyway, can I do this?

+4
source share
5 answers

I assume that each line should be a separate line in the list. Use QTextStream :: readLine () in a loop and at each step add the return 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); } 
+15
source

If the file is not too large, read all the content in QString and then split() in QStringList .

I like to use the QRegExp version to handle line feeds from different platforms:

 QStringList sList = s.split(QRegExp("(\\r\\n)|(\\n\\r)|\\r|\\n"), QString::SkipEmptyParts); 
+2
source
  QFile TextFile; //Open file for reading QStringList SL; while(!TextFile.atEnd()) SL.append(TextFile.readLine()); 
+2
source

I like my code to be completely indented / paranthesized with explicit variable names (they may take longer, but they are much easier to debug), so I would do the following (but changing "myTextFile" and "myStringList" to more reasonable names, for example , "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(); } 
+1
source

The code below 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 ie \ n here \ r - carriage return

  List= ReadAll.split(QRegExp("[\r\n]"),QString::SkipEmptyParts); 
0
source

Source: https://habr.com/ru/post/1340957/


All Articles