Qt:使用QFile和和QTextStream读写文本文件数据

使用QT中的QFile和QTextStream读写文本文件中的数据,具体实现代码如下:

读数据:

QStringList s0, s1;	//s0,s1存放文本文件中的数据,string类型

		QString path = QFileDialog::getOpenFileName(this, "open", "../", "txt(*.txt)");
		if (!path.isEmpty())
		{
			QFile file(path);
			bool isok = file.open(QIODevice::ReadOnly);
			if (isok)
			{
				QTextStream filestream(&file);
				QString str;
				filestream.setCodec("UTF-8");//防止读取数据中文乱码

				while (filestream.atEnd() == false)
				{
					str = filestream.readLine();
					s0 = str.split(" ");
					s1.append(s0);
				}
			}
			else
			{
				QMessageBox::warning(this, "提示", "文件路径为空 !");
			}
			file.close();

写出数据:

//写出数据
QString path = QFileDialog::getSaveFileName(this, "save", "../", "txt(*.txt)");
if (!path.isEmpty())
{
	QFile file(path);
	bool isok = file.open(QIODevice::WriteOnly);
	if (isok)
	{
		QTextStream filestream(&file);
		filestream.setRealNumberPrecision(16);//设置小数位数
		for (int i = 0; i < x2.size(); i++)
		{
			filestream << x2.at(i) << " " << y2.at(i) << " " << z.at(i);
			filestream << "\n";
		}

	}
	file.close();
	QMessageBox::information(this, "提示", "写出成功");
}
else
{
	QMessageBox::warning(this, "提示", "文件路径为空.");
}

你可能感兴趣的:(Qt,qt,c++,读写文本数据)