This might already have been discussed, but I couldn’t find any related topic.
I want to read short values from a file and store them in a buffer of int values using fread. So basically I want to do this:
int *data; //int buffer
data = (int *) malloc(1000 * sizeof(int));
fread(data, sizeof(short), 1000, infile); //infile is organized in 2-byte chunks
Data are stored in a file in 2-byte chunks (short). But when I read those data, I want to put them into an int buffer. How can I do that without copying from a short buffer to an int buffer? fread gets void pointer, so it doesn’t care about the type of buffer.
The
freadfunction doesn’t know about types, that’s correct. That’s why it cant read raw bytes and convert them, it just puts them as-is into the provided buffer. And as you know, ashorton most platforms is two bytes whileintis four. So that will not work asfreadhas not idea about that.You either read one short at a time, putting it into the
intbuffer, or read into a temporaryshortbuffer then loop and copy value by value into theintbuffer.