Search code examples
c++fileifstreameof

Reading text file cause invalid character at buffer end


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?


Solution

  • 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.