简体   繁体   中英

C++/Qt : Invalid STL file - could not read first 6 bytes

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);

I got bytes_read is 4 and so I got :

Invalid STL file - could not read first 6 bytes.

read_binary_file

Invalid binary STL file - could not read 80 byte header.

Invalid binary STL file - could not read number of triangles from binary STL file.

"cube.stl" is .stl file but why would it show like that? Where I wrong? How can I get the vertex coordinates in cube.stl? There is my .stl file: http://www.mediafire.com/download/hnnw444anih201n/cube.stl


Solved

After check and check and check. Finally, I find my way. D*** it, error is simple. I changed path of std::string fname = "cube.stl"; (cube.stl into D:/.../cube.stl). It's amazing. RUN.

You seems to have some confusion on the difference between Ascii and Binary files.

The "rb" flag to fopen will open as a Binary file. Is cube.stl a Binary file? .stl files can be in either Binary or Ascii.

Additionally, how have you validated file size? You are expecting either 6 char in or 80 bytes of binary. Where are those numbers coming from?

In short your problems are:

  • Is cube.stl Ascii?
  • What is the size of the header?
  • What is the format of binary data in an .stl file?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM