I have a partially working function which involves writing to a file.
I have an array, arr
, of type unsigned short int
and each element must be written to a file in binary format.
My inital solution was:
for(i = 0; i < ROWS; i++) {
fwrite(&arr[i], 1, sizeof(unsigned short int), source);
}
The code above works when writing unsigned short ints
to the file. Also, source
is a pointer to the file which is being written to in binary format. However, I need to swap the bytes, and am having trouble doing so. Essentially, what is written to the file as abcd
should be cdab
.
My attempt:
unsigned short int toWrite;
unsigned short int swapped;
for(i = 0; i < ROWS; i++) {
toWrite = &arr[i];
swapped = (toWrite >> 8) | (toWrite << 8);
fwrite(swapped, 1, sizeof(unsigned short int), source);
}
However I get a segmentation fault core dump as a result. I read and used the upvoted answer to this question - convert big endian to little endian in C [without using provided func] - but it doesnt seem to be working. Any suggestions? Thanks!