Binary files

Hi All,

I want to read the contents of a binary file (integer values ) and stor them in an array, but my code is not working ! could any body help me :)

int i;
fstream file ("binaryfile.bin", ios::in|ios::binary);


if (!file)
{
printf("Unable to open file!");
return 1;
}



file.seekg(0, ios::end); // position get-ptr 0 bytes from end

ios::pos_type size = file.tellg(); // get-ptr position is now same as file size

file.seekg (0, ios::beg);

char *p;

p= new int[size];

file.read((char *) &p, sizeof p);


for(i=0; i<10; i++) // show values of the array
cout << p[i] << " ";

file.close();

return 0;
What does it do wrong?
note that size is the size of a file in bytes. you should allocate size/4 integers only.
1
2
for(i=0; i<10; i++) // show values of the array
cout << p[i] << " ";

This wont cout each of the lines in the file. This will cycle through each char and then cout. And don't forget, if you have seperate lines in the file, you'll have to account for the newline constant '\n'.

File:
10
20
30

p[ 0 ] = 1
p[ 1 ] = 0
p[ 2 ] = Newline
p[ 3 ] = takes two
p[ 4 ] = 2
p[ 5 ] = 0
p[ 6 ] = Newline
p[ 7 ] = takes two
p[ 8 ] = 3
p[ 9 ] = 0

Do something like this:
1
2
for( int i = 0; i < 20; ++i )
	std::cout << i << ": " << p[ i ] << '\n';

To see how the file is printed.
Last edited on
Topic archived. No new replies allowed.