C++ FLTK File IO issues

Discussion in 'Mac Programming' started by slooksterPSV, Sep 20, 2005.

  1. slooksterPSV macrumors 68030

    slooksterPSV

    Joined:
    Apr 17, 2004
    Location:
    Nowheresville
    #1
    Code:
    void _open(Fl_Widget *f, void *)
    {
      FILE *fptr = new FILE;
      char *flch;//[80];
      char *flch2 = new char;
      fb = new Fl_File_Chooser("HTML", NULL, 0, NULL);
      fb->show();
      while(fb->visible())
       Fl::wait();
      fptr = fopen(fb->value(), "rb");
      while(!feof(fptr))
      {
      fgets(flch, NULL, fptr);//fread(flch, NULL, NULL, fptr);
      sprintf(flch2, "%s\n%s", stktextbuffer->text(),flch);
      stktextbuffer->text(flch2);
      }
      fclose(fptr);
    }
    There's the code, here's the problem. I've tried doing this many ways, but I can only open one file before the program crashes. If I open a file and it reads it, and click the open button again and choose another file, it crashes. I know this doesn't work with how I have it setup, but could someone help me with this. I've tried a lot of different things. Thanx - if you need all the source lemme know.
     
  2. WebMongol macrumors member

    Joined:
    Sep 19, 2004
    Location:
    Bay Area, CA
    #2
    I would recommend to start with reading about memory allocation and management in C. Next check man pages for fgets and sprintf functions. In Terminal type:
    man fgets
    man sprintf

    The general problem with your code snippet is that you pass uninitialized pointer (flch) or pointer to 1-char buffer to functions that expect pointers to preallocated buffers (allocated on stack or heap). Following statement
    fgets(flch, NULL, fptr);
    does not lead to a crash because buffer size is set to 0 (NULL) otherwise it'll cause a crash
    and this line
    sprintf(flch2, "%s\n%s", stktextbuffer->text(),flch);
    writes formatted string to some heap objects (C++ objects allocated with new or malloc) and your program crashes soon after this call.
    In following snippet I corrected these problems:

    Code:
    void _open(Fl_Widget *f, void *)
    {
      FILE *fptr = NULL;  // (new FILE) is wrong
      char buf[1024];     // allocate memory on stack for tmp buffers
      char buf2[1024];
      fb = new Fl_File_Chooser("HTML", NULL, 0, NULL);
      fb->show();
      while(fb->visible())
       Fl::wait();
      fptr = fopen(fb->value(), "rb");
      while( fgets(buf, sizeof(buf), fptr) ) // read up to sizeof(buf)-1 bytes
      {
      // use snprintf instead of sprintf
      snprintf(buf2, sizeof(buf2), "%s\n%s", stktextbuffer->text(),buf);
      stktextbuffer->text(buf);
      }
      fclose(fptr);
    }
     

Share This Page