Read a binary file that was made by Matlab

Hi,

I am working in a C++ code,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <iostream>
#include <fstream>

using namespace std;

ifstream::pos_type size;
char * memblock;

int main(int argc, char *argv[])
{
	if(argc > 1)
	{
		cout << "Open file: " << argv[1] << endl;
		std::ifstream myFile(argv[1],ios::binary|ios::ate);
		if(myFile.is_open())
		{
			size = myFile.tellg();
			memblock = new char [size];
			myFile.seekg(0,ios::beg);
			myFile.read(memblock,size);
			
			myFile.close();
		}
		cout << "size is: " << size << " bytes" << endl;
		for(int i = 0; i < size; i++)
		{
			cout << "byte[" << i << "]: " << memblock[i] << endl;
		}
	}
	int x = 77;
	std::cout << x << std::endl;
	return 0;
}


The intention is to read the data inside a binary file made by Matlab.

At Matlab I Write:

12345678910

to a binary file.

But with my C++ code I do not get this 12345678910, in fact, I can cout the size (it is correct, ten bytes) but I only retrieve five bytes ( and they are strange things like icons, litlle hearts, ...), the remaining five bits are empy.

I guess the problem is with the quantity of bits I read at a time. How can I only retrieve the first 16 bits of the file?

P.S. At Matlab the data was stored using 16 bits for every 1, 2, 3, ..., 10.


Any comments will be appreciated.
Thanks.
Last edited on
closed account (S6k9GNh0)
1. Watch how you say bits and bytes. There are 8 bits (typically 8: 0000 0000) in one byte. As a result it's confusing. Because it's obvious, I can understand but if you ever talk about bit manipulation or such, it might be confusing.

2. I think you need to use cout.write. The output from read is not a c-string and doesn't contain a NULL character. As a result, cout doesn't know how to interpret the variable. Or I think you could try doing something like this:

1
2
3
4
5
6
size = myFile.tellg();
memblock = new char [size + 1];
myFile.seekg(0,ios::beg);
myFile.read(memblock,size);
memblock[size] = '\0' //I think this is the problem. 
myFile.close();


I can't confirm this problem is actually a problem though because I cannot test it. Thought I think that is what it is.
Last edited on
closed account (z05DSL3A)
...There are 8 bits (0000 0000) in one byte.

Not necessarily. see: http://en.wikipedia.org/wiki/Byte
Last edited on
Topic archived. No new replies allowed.