Michael
Michael

Reputation: 1353

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;
    };
};

Upvotes: 0

Views: 84

Answers (4)

M.M
M.M

Reputation: 141534

To use std::string you need:

#include <string>

The iostream include may have forward-declared std::string but without the full definition you don't get operator<< (or c_str()).

Some other answerers may be unable to reproduce your problem because different standard libraries might have their iostream fully do #include <string> (this is permitted but not required).

Upvotes: 1

user3476093
user3476093

Reputation: 714

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 *

Upvotes: -1

Steephen
Steephen

Reputation: 15824

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

You have to correct above line as follows:

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

DEMO: http://cpp.sh/7b4k

Upvotes: 2

donjuedo
donjuedo

Reputation: 2505

It looks like you need:

#include <iostream>

Upvotes: 1

Related Questions