using ifstream*

Hi,
Most examples for using ifstream don't use ifstream pointers. I thought this would not be a problem but I cannot seem to get my code working. The below gives me the error, "read has not been declared", but fstream is included. I supposed I needed to dereference fp but that changes nothing. Then I thought that the dereferencing might have lower precedence then the dot, so I also tried (*fp).read... which compiles fine but crashes at runtime.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <fstream>
#include <string>
#include <iostream>
using namespace std;
	
void read_data() {
    ifstream f;
    f.open("afile.txt");
    ifstream* fp = &f;

// actually I have f opened elsewhere in the program and this function
// uses a pointer to it but I've included all the relevant code here
// for completeness.

    char* c;
    int len = 5;
    c = new char[50];

    fp.read(c,len);
    cout << c << "\n";
    
    delete[] c;
}


Some help would be fantastic!

regards,
zaph.
You must open your file in binary mode to use read/write.

f.open("afile.txt",ios::binary);

And instead of (*fp).read(/*...*/); you can do fp->read(/*...*/);

This may help -> http://cplusplus.com/doc/tutorial/files/
Last edited on
Topic archived. No new replies allowed.