0

Reading a simple text file in c++ display invalid characters at the end of buffer,

    string filecontent="";
    ifstream reader(fileName);
    reader.seekg (0, reader.end);``
    int length = reader.tellg();
    reader.seekg (0, reader.beg);
    char *buffer=new char[length];
    reader.read(buffer,length);
    filecontent=buffer;
    reader.close();
    cout<<"File Contents"<<std::endl;
    cout<<filecontent;
    delete buffer;
    return false;

but when i specify buffer length incremented by one ie

char *buffer=new char[length+1];
    reader.read(buffer,length+1);

it works fine without invalid characters i want to know what is the reason behind this?

Ali
  • 557
  • 1
  • 9
  • 30
  • 2
    Yep. You need the extra byte for the trailing `'\0'` at the end of the string. You *don't* need to read the extra byte, though. `char *buffer=new char[length+1];` followed by `reader.read(buffer,length);` will do it. – Paul Roub Apr 16 '15 at 16:07

1 Answers1

3

You read a string without terminating it with a trailing zero (char(0) or '\0'). Increase the buffer length by one and store a zero at buffer[reader.tellg()]. Just increasing the buffer size is not good enough, you might get a trailing zero by accident.