QT深入解析数控机床或激光切割机的nc文件包括读取与数据处理技巧
代码功能说明:
这个代码是用来读取一个名为 “C:/QCY/qcy.nc” 的文件,这个文件中包含了一系列数据,每行数据可能包含 X、Y、Z 坐标值。这些坐标值可以代表某种路径或轨迹。
代码的作用是:
- 打开指定路径的文件。
- 逐行读取文件内容。
- 对每一行内容进行匹配,查找是否包含 X、Y、Z 坐标值,并提取出这些值。
- 将提取的 X、Y、Z 坐标值分别存储在
QVector<double>
类型的数组中。 - 如果某行中没有某个坐标值,则默认使用 0 代替。
- 最后,输出每一行的 X、Y、Z 坐标值,以及它们在数组中的索引。
这个代码可以帮助你解析含有 XYZ 坐标值的文件,并将它们存储在内存中以便后续处理或分析。
代码
#include <QFile>
#include <QTextStream>
#include <QDebug>
#include <QRegExp>
void readNetCDFFile(const QString& filePath) {
// Open the file
QFile file(filePath);
if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
qDebug() << "Failed to open the file.";
return;
}
// Arrays to store X, Y, Z values
QVector<double> xValues;
QVector<double> yValues;
QVector<double> zValues;
// Read the content
QTextStream in(&file);
while (!in.atEnd()) {
QString line = in.readLine();
// Regular expression to match X, Y, or Z followed by a number
QRegExp rx("(X|Y|Z)(-?\\d+(\\.\\d+)?)");
// Initialize default values
double xValue = 0.0;
double yValue = 0.0;
double zValue = 0.0;
// Index of the regular expression in the line
int pos = 0;
// Loop to find all matches in the line
while ((pos = rx.indexIn(line, pos)) != -1) {
// Extract the matched text
QString match = rx.cap(1);
// Extract the number part
QString number = rx.cap(2);
double value = number.toDouble();
// Assign the value to the corresponding variable
if (match == "X") {
xValue = value;
} else if (match == "Y") {
yValue = value;
} else if (match == "Z") {
zValue = value;
}
// Move the position forward to search for next match
pos += rx.matchedLength();
}
// Add the values to the arrays
xValues.append(xValue);
yValues.append(yValue);
zValues.append(zValue);
}
// Close the file
file.close();
// Output the values
for (int i = 0; i < xValues.size(); ++i) {
qDebug() << "Line" << i + 1 << "X:" << xValues[i] << "Y:" << yValues[i] << "Z:" << zValues[i];
}
}
int main() {
QString filePath = "C:/QCY/qcy.nc";
readNetCDFFile(filePath);
return 0;
}
运行过程