如何将数据从Qstring列表复制到文本文件以便以后检索? 是否可以在Qt中执行此操作?
如何使用QFile将换行符添加到文本域中我确实喜欢这个
QFile data("output.txt");
if (data.open(QFile::Append ))
{
QTextStream out(&data);
out << fileDet[i];
data.putChar('\n');
}
答案 0 :(得分:4)
查看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 :(得分:1)
您可以执行以下操作:
// 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();
请参阅qt documentation website上有关QFile,QTextStream,QString和QChar的文档。