Home > other >  What is C translation for Matlab‘s `fread()` function?
What is C translation for Matlab‘s `fread()` function?

Time:03-01

I want to translate a MATLAB code to C, but the fread() function of MATLAB confused me a lot, I don't know how to translate it properly. I have used recv() function to read the data, but it's not the same as what I got in MATLAB.

MATLAB code is here:

field_len = fread(t, 1, 'uint16');        % t is a TCP object
code = fread(t,1);
bytes = fread(t, field_len-1, 'uint8');   % field_len > 1

My C code is here(Ignore the code that establishes the TCP link):

uint16_t field_len = 0;
uint8_t code = 0;
uint8_t bytes[field_len-1];

recv(new_server_socket, &field_len, sizeof(field_len), 0);  // new_server_socket is server socket to get data
recv(new_server_socket, &code, sizeof(code), 0);
recv(new_server_socket, bytes, sizeof(bytes), 0);

An numeric example. In MATLAB, field_len should be 213. But in my C code, it is 54528. I don't know what is the problem.

Any insights would be appreciated.

CodePudding user response:

If you want to read 213 bytes you can allocate a 213 byte uint8_t buffer.

uint8_t buffer[213] = {0};
recv(new_server_socket,buffer,sizeof(buffer),0);

This will read 213 bytes if available in the socket into buffer.

If you're trying to read the buffer size from a server and then allocate a buffer of that size which I believe is what you're doing in MATLAB, call recv on the size field, then allocate memory for the buffer dynamically and call recv again.

uint16_t field_len = 0;
uint8_t* buffer = NULL;

recv(new_socket_server,&field_len,sizeof(field_len),0);

buffer = malloc(field_len);
memset(buffer,0,field_len);

recv(new_socket_server,buffer,field_len,0);

I didn't do any error checking but you should always check the return value of recv.

Byte ordering was also mentioned above, if that's the case you can convert network byte ordering to host byte ordering using ntohs after you read field_len

field_len = ntohs(field_len);

Then proceed to allocate memory for the buffer.

  • Related