Search code examples
c++classoopfilebuf

Standard functions and operations not working in class constructor


I am trying to make my first class with a constructor and it seems to be acting strangely. My class is derived from filebuf and for some reason, I am unable to open it in the constructor. I tried to add a cout statement for debugging, but the << operator is not recognized.

#include <iostream>
#include "bin.h"

int main()
{
    bin myBin("e:\Temp\test.txt");


    system("PAUSE");
    return 0;
}

bin.h

#pragma once
#include <fstream>
#include <cstdlib>
#include <cstring>

class bin : private std::filebuf {

int buffSize = 1000;
char* buffer;
unsigned int length;
short int buffCounter;

public:
    bin(std::string fileName)
    {
        open(fileName.c_str(), std::ios::in | std::ios::out | std::ios::trunc);
        if (!is_open())
            std::cout << "ERROR: failed to open file " << fileName << std::endl;

        //set all IO operations to be unbufferred, buffering will be managed manually
        setbuf(0, 0);
        //create buffer
        buffer = new char[buffSize];

    };


     virtual ~bin()
    {
        delete buffer;
    };
};

Solution

  • std::cout << "ERROR: failed to open file " << fileName << std::endl;
    

    Should be

    std::cout << "ERROR: failed to open file " << fileName.c_str() << std::endl;
    

    std::cout doesn't always accept std::string but does accept const char *