POV-Ray : Newsgroups : povray.off-topic : C++ classes and file i/o : C++ classes and file i/o Server Time
5 Sep 2024 23:17:46 EDT (-0400)
  C++ classes and file i/o  
From: stbenge
Date: 13 Apr 2009 19:04:08
Message: <49e3c4e8@news.povray.org>
Hi,

I've got a C++ question, and if somebody here can answer it then I'd be 
happy :) It's probably something super simple, but all my Google 
searches have led to nothing. I'm just now getting into using classes 
and have had success until this point.

I have some code which I use to read a binary file into an array. It 
works flawlessly when I implement it in a non-OO manner using an ugly 
mess of functions and global variables in my main source file. The 
problem comes when I try to do the same thing using classes. Here is my 
loading member function:

void Field::load(int worldX, int worldY, string fileName){
  int tempFx, tempFy;
  int val;
  FILE *fieldFile;
  string fieldFileName;
  fieldFileName=assignName(fileName,worldX, worldY);
  if(fieldFile = fopen(fieldFileName.c_str(), "rb")){
   fread(&tempFx, 2, 1, fieldFile);
   fread(&tempFy, 2, 1, fieldFile);
   for(int y=0;y<fieldHeight;y++){
    for(int x=0;x<fieldWidth;x++){
     fread(&val, 2, 1, fieldFile);
     map[x][y]=val;
    }
   }
   fclose(fieldFile);
  }
  else
  for(int y=0;y<fieldHeight;y++){
   for(int x=0;x<fieldWidth;x++){
    map[x][y]=0;
   }
  }
}

It opens the files just fine, but when it reads values from them into an 
array it returns nonsense. For instance Field.map[0][0] is supposed to 
be 255, but what I get instead is 41746432.

I have tried using ifstreams instead, but I still get the same large 
values even after making sure the file was read from the beginning. I 
have also tried making "map" a new int (and deleting it in the 
destructor), but I get the same large values.

It doesn't make sense to me why this code won't work inside a class, but 
will work just fine elsewhere. Any help would be appreciated. I'm really 
stumped :(

Sam


Post a reply to this message

Copyright 2003-2023 Persistence of Vision Raytracer Pty. Ltd.