0

I want to write a program in C++ so that I can read a file with a file header that has 3 bytes. 1 byte for 1 variable.

I want to define a struct in C++ with 3 variables and all of them has 1 byte so that I can read value from file to these three variables.

My idea is this:

struct header{
    datatype a;
    datatype b;
    datatype c;
}

Then I can:

FILE *fp=fopen(fileName,"rb");
header head;
fread(&head, sizeof(header),1,fp);

Those variables are used for calculating and their range is from 0-255. What datatype I can use in c++?

sflee
  • 1,659
  • 5
  • 32
  • 63
  • I wouldn't normally downvote for this question, but you're asking "what datatype in C++ is 1 byte". That's proof that there was no research done here. – Will Custode Oct 23 '13 at 16:01
  • I know char has size 1 byte, but I need calculating. I mean when I do : `char a = 10; a += 1; cout << a;` That is not what I want. And I am not sure what to do. – sflee Oct 23 '13 at 16:09
  • 1
    `char` has size 1 _on most platforms_. Don't rely on it. Also, `char` is an integral type. You can use it to make calculations. Just cast it before printing: `cout << (int)a;`. – Guilherme Bernal Oct 23 '13 at 16:12
  • 1
    Also, this other question may be relevant to your problem: http://stackoverflow.com/questions/4306186/structure-padding-and-structure-packing – Guilherme Bernal Oct 23 '13 at 16:14

2 Answers2

4

Use uint8_t included in <cstdint> for datatype which has 1 byte length.

masoud
  • 55,379
  • 16
  • 141
  • 208
  • But the bits read will be exactly the same, and how the compiler treats it could be irrelevant if the OP wants to read them individually for example. – Bartek Banachewicz Oct 23 '13 at 17:20
1

You can use char, that's exactly 1 byte.

Nicholas Smith
  • 11,642
  • 6
  • 37
  • 55