【问题标题】:C++/Qt : Invalid STL file - could not read first 6 bytesC++/Qt:无效的 STL 文件 - 无法读取前 6 个字节
【发布时间】:2018-05-19 23:56:37
【问题描述】:
std::string fname = "cube.stl";
FILE *inf = std::fopen(fname.c_str(), "rb");
if (inf == NULL) {
    //throw std::runtime_error(std::string("Cannot open file ") + fname);
    qglColor(Qt::black);
    this->renderText(10, 10, "Cannot open file ");
}
char buffer[6];
size_t bytes_read = fread(buffer, 1, 6, inf);//copy file to buffer
QString bytes_read_diaplay = QString::number(bytes_read);
qglColor(Qt::black);
this->renderText(10, 300, bytes_read_diaplay);

if (bytes_read != 6) {
    qglColor(Qt::black);
    this->renderText(10, 10, "Invalid STL file - could not read first 6 bytes.");
}

std::rewind(inf);

if (0 == std::memcmp(buffer, "solid ", 6)) {
    //read_ascii_file(inf);
    qglColor(Qt::black);
    this->renderText(10, 30, "read_ascii_file");
} else {
    //read_binary_file(inf);
    qglColor(Qt::black);
    this->renderText(10, 30, "read_binary_file");
    char buffer[80];
    size_t num_read = fread(buffer, 1, 80, inf);
    if (num_read != 80) {
        qglColor(Qt::black);
        this->renderText(10, 50, "Invalid binary STL file - could not read 80 byte header.");
    } 
    std::memcpy(header, buffer, 80);

    unsigned int num_tris = 0;
    num_read = std::fread(&num_tris, sizeof(unsigned int), 1, inf);
    if (num_read != 1) {

        qglColor(Qt::black);
        this->renderText(10, 70, "Invalid binary STL file - could not read number of triangles from binary STL file.");
    }


}
std::fclose(inf);

我得到 bytes_read 是 4,所以我得到了:

无效的 STL 文件 - 无法读取前 6 个字节。

读取二进制文件

无效的二进制 STL 文件 - 无法读取 80 字节的标头。

二进制 STL 文件无效 - 无法从二进制 STL 文件中读取三角形数量。

"cube.stl" 是 .stl 文件,但为什么会这样显示?我哪里错了?如何获取 cube.stl 中的顶点坐标? 有我的 .stl 文件:http://www.mediafire.com/download/hnnw444anih201n/cube.stl


已解决

检查后检查再检查。最后,我找到了自己的方式。 D***吧,错误很简单。我改变了 std::string fname = "cube.stl"; 的路径(cube.stl 到 D:/.../cube.stl)。太奇妙了。运行。

【问题讨论】:

  • 您应该在调用fread 后立即检查读取的字节数,而不是在调用可能影响bytes_read 值的2 个函数后等待。其次,我们没有您的文件,因此我们不知道它是否以某种方式损坏。
  • 你可以留在 Qt-land 没有标准调用,使用 QFile 等。如果文件有 6 个字节,它实际上应该返回 6。但我同意 @PaulMcKenzie 没有要读取的文件我们无能为力。

标签: c++ qt stl


【解决方案1】:

您似乎对 Ascii 和二进制文件之间的区别有些混淆。

fopen 的“rb”标志将作为二进制文件打开。 cube.stl 是二进制文件吗? .stl 文件可以是 Binary 或 Ascii。

此外,您如何验证文件大小?您期望 6 char in 或 80 字节的二进制文件。这些数字是从哪里来的?

简而言之,您的问题是:

  • cube.stl 是 Ascii 吗?
  • 标题的大小是多少?
  • .stl 文件中二进制数据的格式是什么?

【讨论】:

    猜你喜欢
    • 2015-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-24
    • 1970-01-01
    • 2019-04-18
    • 2012-04-15
    相关资源
    最近更新 更多