ifstream Object's .read() Problems of *char

50 views Asked by At

My code:

ifstream Reader ("commands.txt");
if(Reader.fail())
{

    error("File \"commands.txt\" could not be found or opened.\n");

}

Reader.seekg(0, Reader.end);
int FSize = Reader.tellg();

if(FSize == 0)
{

    cout << "File \"commands.txt\" is empty.\n";
    return 0;

}

char * ContentsHold = {};
Reader.read(ContentsHold, FSize);
Reader.close();

string Contents(ContentsHold);

The idea is that at the end, Contents should be a c++ string that holds everything in commands.txt. I get the error "basic_string::_S_construct null not valid". I can't figure out what is going wrong. Help?

1

There are 1 answers

0
David G On

What you have here,

char* ContentsHold = {};

declares a pointer to character initialized with a null constant. This is not a pointer to the first element of an array, you would have to use the new[] syntax for that:

char* ContentsHold = new char[FSize];

This will create an array and ContentsHold will point to its first element. Even better would be to use std::string and expose the address of its first element:

std::string ContentsHold(FSize);
Reader.read(&ContentsHold[0], FSize);

This way you won't have to worry about deleting the new'd memory.