使用QTextStream类实现流(Stream)式操作读写文本
时间: 2024-05-01 07:22:23 浏览: 14
QTextStream类提供了一种方便的方式来读写文本数据。它可以与QIODevice及其子类一起使用,例如QFile和QTcpSocket。以下是使用QTextStream读写文本的示例:
```cpp
#include <QFile>
#include <QTextStream>
#include <QDebug>
int main()
{
QFile file("example.txt");
if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
qDebug() << "Failed to open file";
return 1;
}
QTextStream in(&file);
while (!in.atEnd()) {
QString line = in.readLine();
qDebug() << line;
}
file.close();
QFile outputFile("output.txt");
if (!outputFile.open(QIODevice::WriteOnly | QIODevice::Text)) {
qDebug() << "Failed to open file";
return 1;
}
QTextStream out(&outputFile);
out << "Hello, World!" << endl;
out << "This is a sample output." << endl;
outputFile.close();
return 0;
}
```
在上面的示例中,我们首先打开一个名为example.txt的文件,并使用QTextStream从中读取每一行。我们还打开了一个名为output.txt的文件,并使用QTextStream将一些文本写入该文件。请注意,在写入文本时,我们还使用了endl,这将在输出结束时自动添加一个换行符。
QTextStream还提供了许多其他方法,例如read()和write(),用于读取和写入QString和QByteArray类型的数据。它还提供了一些格式化输出方法,例如setFieldWidth()和setPadChar(),这些方法可以帮助您以您喜欢的格式输出数据。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)