Скопировать из QStringList в текстовый файл - PullRequest
2 голосов
/ 09 апреля 2010

Как скопировать данные из списка Qstring в текстовый файл для последующего извлечения? Возможно ли это сделать в Qt?

Как поместить символ новой строки в текстовое поле, используя QFile. Мне это понравилось

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

Ответы [ 2 ]

4 голосов
/ 09 апреля 2010

Взгляните на http://doc.qt.io/archives/4.6/qfile.html#details и http://doc.qt.io/archives/4.6/qtextstream.html#details.

Пример кода:

#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';
}
1 голос
/ 09 апреля 2010

Вы можете сделать что-то вроде следующего:

// 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();

См. Документацию по QFile, QTextStream, QString и QChar, все они доступны на веб-сайте qt с документацией .

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...