I want to write a file_handle class like this
#include <stdio.h>
#include <iostream>
#include <string>
//===========================================================================
class File_handle {
FILE* p;
public:
File_handle(const char* pp, const char* r) {
p = fopen(pp, r);
}
File_handle(const std::string& s, const char* r) {
p = fopen(s.c_str(), r);
}
~File_handle() {
if (p)
fclose(p);
}
// what is this ????? i found it in stroustrups c++ on page 389
// ---> Mark A
operator FILE*() { return p;}
// I have tried something like this, but without any success
// ---> Mark B
//friend std::ostream& operator<<(std::ostream&, const File_handle&);
};
//===========================================================================
int main() {
const std::string filename("test.txt");
File_handle fh(filename, "w");
// doesn't work
// fh << "hello\n";
// *fh << "hello\n";
// this works now
File_handle fA("A.txt", "w");
fprintf(fA, "say hello to A.txt");
File_handle fB("B.txt", "w");
fputs("say hello to B.txt", fB);
return 0;
}
I don’t know, how I can use the file stream outside the class.
I have tried it with overloading the operator<<, how you can see in the code example above. (Indicated as: mark B in the code above.)
And I found the line operator FILE*() { return p; } in the book of Bjarne Stroustrup.
But which operator is overloaded in this line? (Indicated as: mark A)
You should use
std::fstreaminstead of yourFile_handleclass.But if you need to specify some additional behaviour, you can derive your class from
std::fstream. So this kind of solution could look like this:Hope this helps.