Problem with writing byte

Hi all

I am trying to write an array in a file in bytes. I can write file if the values are lower than 255.

I am using fwrite:

fwrite(&myArray[i],1,1,file);

But for the values greater than 255, I need to write these numbers into 2 bytes. How can I do this?

Thanks
Kenter
Last edited on
i guess fwrite(&myArray[i],sizeof(myArray[i]),1,file); this way? What's the type of the array? Why don't you write the whole array at once?
Thanks for the reply.

I have an array of integer. I want to create a monochrom (black to white) image. So each pixel will have a number coming form the array.

When the array contains only numbers lesser than 255, I just write these values to the corresponding pixels. And it works fine. But if I have a number which is great than 255, I can not directly write it because I guess char can take values between 0-255. My image format is "VICAR" maybe you have not heard this before but it supports also the values greater than 255. So somehow, I need to write a number like 300 into 2 bytes.

Is there a way to write it at once?

fwrite(&myArray[i],2,1,file); doesnt work.

Cheers
fwrite(&myArray[i],2,1,file); doesnt work.


This actually does work. (although it's not endian safe -- but whatever).

Your problem sounds like it has less to do with file I/O and more to do with converting to/from this VICAR format.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <iostream>

namespace little_endian_io
  {
  template <typename Word>
  std::ostream& write_word( std::ostream& outs, Word value, unsigned size = sizeof( Word ) )
    {
    for (; size; --size, value >>= 8)
      outs.put( static_cast <char> (value & 0xFF) );
    return outs;
    }

  template <typename Word>
  std::istream& read_word( std::istream& ins, Word& value, unsigned size = sizeof( Word ) )
    {
    for (unsigned n = 0, value = 0; n < size; ++n)
      value |= ins.get() << (8 * n);
    return ins;
    }
  }

namespace big_endian_io
  {
  template <typename Word>
  std::ostream& write_word( std::ostream& outs, Word value, unsigned size = sizeof( Word ) )
    {
    while (size)
      outs.put( static_cast <char> ( (value >> (8 * --size)) & 0xFF );
    return outs;
    }

  template <typename Word>
  std::istream& read_word( std::istream& ins, Word& value, unsigned size = sizeof( Word ) )
    {
    for (value = 0; size; --size)
      value = (value << 8) | ins.get();
    return ins;
    }
  }

INTFMT=HIGH --> big-endian
INTFMT=LOW --> little-endian

1
2
if (INTFMT=="INTFMT=HIGH") big_endian   ::write_word( f, pixel_value, 2 );
else                       little_endian::write_word( f, pixel_value, 2 );

Hope this helps.
Thanks for all replies.

With your help, I solved the problem.

Cheers
Kenter
Topic archived. No new replies allowed.