Saltin8R
Saltin8R

Reputation: 37

How do I read in data from an external binary file that needs differing byte lengths per element?

Here's the situation. I have to read in data from an external binary file and display the data in order and so that it makes sense to the user.

The file has data stored as follows: the first 4 bytes are an integer, then the next 8 bytes are a floating decimal, followed by the next 8 bytes (float), etc. So I need to read in 4 bytes initially, then repeatedly 8 bytes after that... until the file has no data left to read.

I have read the file in such a way that it stores its data into an array i[NUM] (where NUM is the number of elements), and each element contains 4 bytes. By doing this, I have accidentally 'split' the floats in half, the first half being stored in i[1] and the second half in i[2], also a float in i[3] and i[4], etc.

Now I am in the process of trying to 'stitch' the two halves of each float back together again in order to display them, but I am stuck.

Any suggestions are greatly appreciated.

My code so far:

#include "stdafx.h"
#include "stdio.h"

#define NUM 15

int main(void)
{
//initialising
int i[NUM], j, k;
float temp[NUM];
char temp_c[NUM];
int element_size = 4;
int element_number = NUM;
for(k=0; k<NUM; k++)
{
    i[k] = 0; //clear all cells in i[]
    temp[k] = 0; //clear all cells in temp[]
}

//file reading
FILE *fp;
fp = fopen("C:\\data", "rb+");
fread(&i, element_size, element_number, fp); //reads 'data' to the end and then stores each element into array i[]
fclose(fp); //close the file

//arrange and print data here
printf("Data of File\n\nN = %d",i[0]);

//this is where the rest fell apart
    //No idea how to go about it

return 0;
}

Upvotes: 2

Views: 86

Answers (1)

M.M
M.M

Reputation: 141544

If you're sure that the float is 8 bytes and the int is 4 then you can do this (probably in a loop with variables instead of the fixed indices I've used):

memcpy(&temp[0], &i[1], 8);

I'm assuming that your code for creating the file was a fwrite where you wrote the 4-byte int, then wrote the 8-byte floats.

Then you can output the floats with printf("%f\n", temp[0]); or whatever.

NB. You can avoid your initialization loop by initializing the arrays directly: int i[NUM] = { 0 }; etc. This only works for 0, not for other values.

Upvotes: 1

Related Questions