DaniWeb IT Discussion Community

DaniWeb IT Discussion Community (http://www.daniweb.com/forums/index.php)
-   C++ (http://www.daniweb.com/forums/forum8.html)
-   -   how to read a binary file data to a monitor (http://www.daniweb.com/forums/thread141725.html)

mksakeesh Aug 22nd, 2008 9:44 am
how to read a binary file data to a monitor
 
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();
}

jencas Aug 22nd, 2008 11:24 am
Re: how to read a binary file data to a monitor
 
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[size]; by memblock = new char[size + 1]; memblock[size] = 0;

niek_e Aug 22nd, 2008 11:39 am
Re: how to read a binary file data to a monitor
 
You would also need to delete the memory you've freed, or else you'll get a memory leak

Salem Aug 22nd, 2008 12:48 pm
Re: how to read a binary file data to a monitor
 
Both suffer from having void main as well.


All times are GMT -4. The time now is 7:21 am.

Forum system based on vBulletin Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
©2003 - 2009 DaniWeb® LLC