0

A program crashes if I try to use ifstream while having OpenGL/freeglut. My code:

#include <fstream>
#include <windows.h>
#include <GL/freeglut.h>
double x, y;
std::ifstream read("coordinates.txt");
void display() {
    glBegin(GL_LINE_STRIP);
        while (read >> x) //Crashes here
        {
            read >> y;
            glVertex2d(x, y);
        }
    glEnd();
    glFlush();
}
void key(unsigned char mychar, int x, int y) {
    if (mychar == 27) {
        exit(0);
    }
}
void initialize()
{
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluOrtho2D(-27, 27, -27, 27);
}
int main(int argc, char **argv) {
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_RGB | GLUT_SINGLE);
    glutInitWindowSize(1920, 1080);
    glutInitWindowPosition(0, 0);
    glutCreateWindow("Lorenz Attractor");
    initialize();
    glutDisplayFunc(display);
    glutKeyboardFunc(key);
    glColor3d(0, 0, 1);
    glutFullScreen();
    glutMainLoopEvent();
    Sleep(60000);
}

coordinates.txt:

1.1 1.03
2.5 2
3 5.3

I don't even need to include freeglut, I checked out an older project that was working perfectly before and now it crashes as well. Using Code::Blocks with MinGW. Why would this happen? Thanks!

DDomjosa
  • 113
  • 6

1 Answers1

1

display will be called more than one time. It's called whenever the display needs to be redrawn, such as when the window comes into view, another window is moved over top of it, the window is resized, etc.

display reads a file. Well, after the first time it reads the file, the file will be empty. After all, you opened the file in a global variable (FYI: never do that), and you kept reading until the file was empty.

Don't read files while you're drawing. Read the file into a data structure (say, a vector<float>). Do that before the rendering loop. Then, use the data structure to draw from.

Nicol Bolas
  • 449,505
  • 63
  • 781
  • 982
  • I used glutMainLoopEvent(), display will only run once. Also, storing the file in a data structure isn't an option, because I'll eventually need this to draw graphs from 100s of thousands of coordinates, so I'll run out of memory pretty quickly. Also this doesn't explain why ifstream doesn't work at all, even with no freeglut. – DDomjosa Dec 29 '15 at 14:24