Trying to write .ply parser to use .ply models in OpenGL.
Trying to begin to read the .ply file and write all the lines of it out.
My program does this but when it print out the last line i get Unhandled exception:
Unhandled exception at 0x62aad540 (msvcr100d.dll) in PLY parser.exe: 0xC0000005: Access violation reading location 0x00000000.
This is my code:
#include <iostream>
#include <fstream>
#include <string>
#include <stdio.h>
using namespace std;
int main ()
{
char buffer[10000];
FILE * myFile;
myFile = fopen("walkman.ply", "r");
if(myFile != NULL)
{
while (!feof(myFile))
{
cout<<fgets(buffer, 10000, myFile);
}
fclose(myFile);
}
else
{
cout<<"file not found"<<endl;
}
system("pause");
return 0;
}
This may be foolish error in my code, but it would be great if someone can spot the error causing this.
Before we get into what the bug is, you should know that the “Unhandled exception … Access violation reading location 0x00000000” message you get is not caused by a C++ exception; it’s the Windows equivalent of “Segmentation fault”. Your code tried to dereference the NULL pointer.
Now, you have made one of the classic mistakes in working with
FILEobjects.feof(fp)does not become true when you reach the end of the file. It only becomes true after you have attempted to read past the end of the file at least once. Thus, your read loop will iterate until afterfgetsattempts to read past the end of the file. And whenfgetsattempts to read past the end of the file, it fails, and returns a NULL pointer, which you blindly passed tocout. Kaboom.(By the way, this is also how
istream::eof()works.)The correct way to write this loop is
(Or, even better, one of these:
it being a little weird to mix
stdio.hFILEs andiostreams as you are doing.)