varuog
varuog

Reputation: 3081

C++ ifstream appending garbage data while reading from a text file

char* readFromFile(char* location)
{
    int total = 0;
    ifstream ifile = ifstream(location);
    ifile.seekg(0, ifile.end);
    total = ifile.tellg();

    cout << "Total count" << total << endl;
    char* file = new char[total+1];

    ifile.seekg(0, ifile.beg);

    ifile.read(file, total+1);

    cout <<"File output" << endl<< file << "Output end"<<endl;

    return file;
}

here it is printing the file data but it also appending some garbage value. how should I fix it?

Upvotes: 2

Views: 2368

Answers (1)

Dominique McDonnell
Dominique McDonnell

Reputation: 2520

read just reads a number of bytes, it doesn't null terminate the sequence. While cout expects a null terminated sequence, so it continues to print random memory that is located after your array until it runs into a 0. So you need to allocate one extra character, and then fill it with a null character.

char* readFromFile(char* location)
{
    int total = 0;
    ifstream ifile = ifstream(location);
    ifile.seekg(0, ifile.end);
    total = ifile.tellg();

    cout << "Total count" << total << endl;
    char* file = new char[total+1];

    ifile.seekg(0, ifile.beg);

    ifile.read(file, total); //don't need the +1 here

    file[total] = '\0'; //Add this

    cout <<"File output" << endl<< file << "Output end"<<endl;

    return file; 
}

Upvotes: 5

Related Questions