#include <iostream>
#include <fstream>
#include <string.h>
#include <cstdlib>
#include <ctype.h>
#include <stdlib.h>
using namespace std;
class W_File_of_Int : public ofstream {
private:
ofstream _fout;
public:
W_File_of_Int(const char* nom_fic)
{
ofstream _fout(nom_fic, ios::out | ios::binary);
cout << "\n\tfile of int to write is ready";
}
~W_File_of_Int()
{
cout << "\n\tDestruction of file to write\n";
_fout.close();
}
int tellp() { return ofstream::tellp(); }
W_File_of_Int& operator<<(int i)
{
_fout.write((char*)&i, sizeof(int));
return *this;
}
};
int main()
{
W_File_of_Int f_out("essai.fic");
if (!f_out) {
cerr << "\nErreur dansla creation de 'essai.fic'\n";
return 1;
}
for (int i = 0; i <= 10; i ) // Ecriture de 11 entiers dans le fichier
f_out << i;
cout << f_out.tellp() << "\n\telements sont ecrits dans le fichier.\n";
// affiche: 11 elements sont ecrits dans le fichier.
f_out.close();
return 0;
}
I tried many times ,like make int to &int,it just don`t work
write with overloaded "<<",but failed, file is still empty.
CodePudding user response:
Your constructor has access to 3 different ofstream
instances:
- The base class
- The member variable
this->_fout
- The local variable
_fout
.
You should probably use the base class only, for which you would need to change the constructor:
W_File_of_Int(const char* nom_fic) :
ofstream(nom_fic, ios::out|ios::binary) // call base class constructor
{
cout << "\n\tfile of int to write is ready";
}
CodePudding user response:
class W_File_of_Int : public ofstream
{
private:ofstream _fout;
.......
here you create two ofstream : _fout AND the base class;
you should choose one