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();
}

Recommended Answers

All 3 Replies

Member Avatar for jencas

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;

You would also need to delete the memory you've freed, or else you'll get a memory leak

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.