1

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.

ljedrz
  • 20,316
  • 4
  • 69
  • 97
aminfar
  • 2,297
  • 3
  • 27
  • 37
  • 1
    Do not cast malloc: http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc – ljedrz Dec 04 '12 at 20:18

3 Answers3

3

The fread function 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, a short on most platforms is two bytes while int is four. So that will not work as fread has not idea about that.

You either read one short at a time, putting it into the int buffer, or read into a temporary short buffer then loop and copy value by value into the int buffer.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
1

Naja, you have to do that "copying from a short buffer to an int buffer", because if you just read your infile into data, it will just copy byte by byte from your file to the memory called data thus writing 2 shorts into one int.

pbhd
  • 4,384
  • 1
  • 20
  • 26
1

1) You can use fscanf with %hu and this works if the actual values are in text format, not binary.

unsigned short a
fp = fopen("myfile","r");
while(fscanf(fp,"%hu",&a))
{
    // put a in the array of unsigned short
}

2) You can use fscanf with %c and this works if the actual values are in binary format.

unsigned short a;
char b,c;
fp = fopen("myfile","r");
while(fscanf(fp,"%c",&b) && fscanf(fp,"%c",&c))
{
    a = (unsigned short) b;
    a = a << 8;
    a+= (unsigned short) c;
    // put a in the array of unsigned short
}
MOHAMED
  • 41,599
  • 58
  • 163
  • 268