Please compare the two codes below why is the first one displaying output to monitor where as the second code is displaying some unwanted characters.

CODE 1 .....

#include <fstream.h>
#include <string.h>

void main()
{
    fstream File("test_file.txt",ios::out | ios::in | ios::binary );

    char arr[13];
    strcpy(arr,"Hello World!"); //put Hello World! into the array

    File.write(arr,5); //put the first 5 symbols into the file- "Hello"

    static char read_array[10]; //I will put the read data, here

    File.seekg(ios::beg);
    File.read(read_array,5); //read the first 3 symbols- "Hel"

    cout << read_array << endl; //display them

    File.close();
}

CODE 2....

#include <fstream.h>
#include <string.h>

void main()
{
    fstream File("test_file.txt",ios::out | ios::in | ios::binary );
    char * memblock;
    ifstream::pos_type size;
    //int size;

    File.seekg(ios::ate);
    size = File.tellg();
    memblock = new char[size];
    File.read(memblock,size);

    //cout<<*memblock;
    //cout<<"\n";
    cout<<memblock;

    File.close();
}

Edited 3 Years Ago by mike_2000_17: Fixed formatting

CODE 1 may end in problems, too, because of the missing terminating 0 in read_array

CODE 2 is missing a rewind to begin of file before File.read(memblock,size); and has the same problem with the terminating 0. Replace memblock = new char; by memblock = new char; memblock = 0;

This article has been dead for over six months. Start a new discussion instead.