逐行读取文件
QT
在 Qt 中,你可以使用 QFile
和 QTextStream
来逐行读取文件。下面是一个示例代码,演示了如何逐行读取文件:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <QFile>
#include <QTextStream>
void readFileLineByLine(const QString& filePath)
{
QFile file(filePath);
if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
{
qDebug() << "Failed to open the file.";
return;
}
QTextStream in(&file);
while (!in.atEnd())
{
QString line = in.readLine();
// 处理每一行的内容
qDebug() << line;
}
file.close();
}
C++
在 C++ 中,你可以使用标准库中的 ifstream
类来逐行读取文件。以下是一个示例代码,演示了如何逐行读取文件:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <fstream>
#include <string>
void readFileLineByLine(const std::string& filePath)
{
std::ifstream file(filePath);
if (!file.is_open())
{
std::cout << "Failed to open the file." << std::endl;
return;
}
std::string line;
while (std::getline(file, line))
{
// 处理每一行的内容
std::cout << line << std::endl;
}
file.close();
}
这属于基础知识了,但是现在还是QT用的最多,读文件,写文件,如果要速度的话,还是得用C的方法来操作。