-
How does fread() work.
Hello, Ive got an assignment to do, that requires I take a .dat file, with data points sorted like this:
x1 y1 x2 y2 etc.
Unfortunately its arranged for bigendian pcs and one of the assignment takes is to change it to littlendian so the data actually means something,
This is the code I have so far. Basically I know that I have to read in the data, put them into a union as an integer, do bitwise operations on them to rearrange into littleend, and then return that union as a wonderful new float that means something.
I just don't know how fread() works. I've read up on it online, but...its not very clear.
If I have 10 numbers to read, how do i tell it to put them into 10 unions? Is this how it does things normally?
I kind of want teaching more than the answer, if thats k.
Thanks alot.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>
int status;
FILE *data;
int no_of_floats;
int no_of_datapoints;
typedef struct{
double x_value;
double y_value;
}data_point;
typedef union{
int data_dummy;
}converter;
int main(int argc, char** argv)
{
struct stat file_status;
data_point* data_value;
converter* data_converter;
int datacheck;
data = fopen("px390_2_bin.dat", "r");
if (data == NULL) /*Test for error*/
{
printf("Error opening file.\n");
exit(8);
}
if (stat("px390_2_bin.dat", &file_status) != 0)
{
perror("Could not find the size of the file 'px390_2_bin.dat'\n");
}
else
{
printf("The size of the file is: %ld\n", file_status.st_size);
}
no_of_floats = file_status.st_size/sizeof(float);
printf("The number of data values in the file is: %d\n", no_of_floats);
no_of_datapoints = no_of_floats / 2;
data_value = (data_point*)malloc(sizeof(data_point) * no_of_datapoints);
data_converter = (converter*)malloc(sizeof(int) * no_of_floats);
datacheck = fread((char *)&data_converter, sizeof(int), no_of_floats, data);
if (datacheck != no_of_floats)
{
printf ("Error writing data to file.\n");
}
else
{
printf ("Successfully wrote data to file.\n");
}
printf("datacheck = %d\n", datacheck);
printf("no_of_floats = %d\n", no_of_floats);
printf("The first int is: %d\n", data_converter[1].data_dummy);
free(data_value);
return 0;
}
-
I've kinda figured it out through plain desperation.
My fread line should have been this:
Code:
datacheck = fread(data_converter, sizeof(int), no_of_floats, data);
As in it didn't need a pointer to memory, I think thats because I'd already assigned data_converter its memory using malloc previously, so I guess it just needed to know what array of unions I wanted to put everything into.
Feel free to confirm this though, one of you experienced folk :)