0

I've got a "strange" problem in writing/reading binary values:

bool readHeader(std::fstream &file)
{
    file.seekg(0);
    int a = file.tellg();
    file.get(reinterpret_cast<char*>(&a), sizeof(a));
    int b = file.tellg();
    file.get(reinterpret_cast<char*>(&b), sizeof(b));
    int c = file.tellg();
    file.seekg(32);
    return !(file.bad());
}

bool writeHeader(std::fstream &file)
{
    file.seekg(0);
    int a = file.tellg();
    file.write(reinterpret_cast<char*>(&a), sizeof(a));
    int b = file.tellg();
    file.write(reinterpret_cast<char*>(&b), sizeof(b));
    int c = file.tellg();
    file.seekg(32);
    return !(file.bad());
}

Where 'a' is uint32_t and 'b' is uint64_t.

What is strange here - variables a, b and c has following values:

in readHeader: 0, 3, 10

in writeHeader: 0, 4, 12

And this cause, that I would have to make a:

file.seekg(1, std::ios_base::cur);

After each get operation. Is it correct? Am I doing something so wrong?

Dejwi
  • 4,393
  • 12
  • 45
  • 74

1 Answers1

1

Use read().

get() extracts upto n-1 characters or \n of EOF or error(whichever 1st) into a C style string

read extracts upto n charcters or EOF(whichever 1st) into any memory location.

Bug Killer
  • 661
  • 7
  • 22