tags:

views:

262

answers:

2

How do I copy data from a Qstring list to a text file for later retrieval? Is it possible to do this in Qt?

How to put a newline character into a text fiel using QFile I did like this

QFile data("output.txt"); 
if (data.open(QFile::Append )) 
{ 
 QTextStream out(&data);  
 out << fileDet[i]; 
 data.putChar('\n');
}
A: 

Take a look at http://doc.trolltech.com/4.6/qfile.html#details and http://doc.trolltech.com/4.6/qtextstream.html#details.

Some example code:

#include <QFile>
#include <QStringList>
#include <QTextStream>
#include <cstdlib>
#include <iostream>

int main() {
  QStringList l;
  l += "one";
  l += "two";

  // write data
  QFile fOut("file.txt");
  if (fOut.open(QFile::WriteOnly | QFile::Text)) {
    QTextStream s(&fOut);
    for (int i = 0; i < l.size(); ++i)
      s << l.at(i) << '\n';
  } else {
    std::cerr << "error opening output file\n";
    return EXIT_FAILURE;
  }
  fOut.close();

  // read data
  QStringList l2;
  QFile fIn("file.txt");
  if (fIn.open(QFile::ReadOnly | QFile::Text)) {
    QTextStream sIn(&fIn);
    while (!sIn.atEnd())
      l2 += sIn.readLine();
  } else {
    std::cerr << "error opening output file\n";
    return EXIT_FAILURE;
  }

  // print
  for (int i = 0; i < l2.size(); ++i)
    std::cout << qPrintable(l2.at(i)) << '\n';
}
mkj
My aim is to put a newline character, rest all character i put
How to put a newline character into a text fiel using QFileI did like this QFile data("output.txt"); if (data.open(QFile::Append )) { QTextStream out( out << fileDet[i]; data.putChar('\n');
I'm not sure I understand your question. `putChar` should probably work, but you can use `out << '\n'` also.
mkj
Btw, I'm not sure if it's safe to operate the `QFile` with `putChar` while using a `QTextStream` on the file at the same time.
mkj
Her ei did the same u give out << fileDet.at(i)<<'\n';I am getting Unknow character
+1  A: 

You can do something like the following:

// first, we open the file
QFile file("outfile.txt");
file.open(QIODevice::WriteOnly);

// now that we have a file that allows us to write anything to it,
// we need an easy way to write out text to it
QTextStream qout(&file);

// I can write out a single ASCII character doing the following
qout << QChar((int)'\n');
// But when you're dealing with unicode, you have to be more careful
// about character sets and locales.

// I can now easily write out any string
QString text("Hello!");
qout << text;

// and when you're done, make sure to close the file
file.close();

See the documentation on QFile, QTextStream, QString, and QChar all of which is available on the qt documentation website.

Kaleb Pederson
Same thing i did but getting unknown character instead of newline
I removed Unicode from project properties>c/c++>preprocessor, then also same unknown character
Please add your full error to your post.
Kaleb Pederson
The c/C++ preprocessor unicode property doesn't change the general Qt unicode handling.
Kaleb Pederson