I have a class with an ifstream pointer as a class member, e.g.
class SomeClass {
...
ifstream* binary_file;
...
public:
...
void randomMethod();
...
}
In one of the methods, e.g. randomMethod() I tried to open a file in binary mode by executing binary_file->open(filename, ios::binary);
, but this caused a segfault.
I then tried to create a temporary ifstream and then point the pointer to that ifstream like so:
ifstream temp (filename, ios::binary);
binary_file = &temp;
The above code didn't cause a segfault, and I was able to do some processing on the file within this method. However, trying to access it in a different class method, I started to get errors. I presume this is due to the memory that was allocated to temp getting deallocated after the method returns and thus my pointer pointing to an arbitrary memory location.
How can I initialize an ifstream object and keep it attached to my class for later access? (I do attempt to close this file in the deconstuctor but obviously there is nothing to close...)
Thanks!