Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>This is because <code>sizeof(char) == 1</code> and <code>sizeof(int) == 4</code>. The <code>std::ostream::write(const char*, size_t)</code> function interpret its last argument as the number of bytes to write. So when you write, you only write 2 bytes. The <code>std::istream::read(char*, size_t)</code> function also interpret its last argument as a number of bytes to read.</p> <p>So, using some diagram to represent you code, we have:</p> <pre><code>fstream F ( soubor1, ios::out | ios::binary ); unsigned int x = 0xc4; // x = // ,---------------------------. // | 0xc4 | 0x00 | 0x00 | 0x00 | // `---------------------------' F.write((const char*)&amp;x, 1); // This write the first byte of x into the file, // that is it write the byte 0xc4 x = 0x8d; // x = // ,---------------------------. // | 0x8d | 0x00 | 0x00 | 0x00 | // `---------------------------' F.write((const char*)&amp;x, 1); // This write the first byte of x into the file, // that is it write the byte 0x8d F.close(); F.open( soubor1, ios::in | ios::binary ); unsigned int a[2]; // a = // ,-------------------------------------------------------. // | ?? | ?? | ?? | ?? | ?? | ?? | ?? | ?? | // `-------------------------------------------------------' F.read((char*)&amp;a[0], 2); // a = // ,-------------------------------------------------------. // | 0xc4 | 0x8d | ?? | ?? | ?? | ?? | ?? | ?? | // `-------------------------------------------------------' // You just read two bytes, while a point to a region that is // 8 bytes long. So only the first two bytes of the first int // are initialized, all the other value are undefined. </code></pre> <p>You can correct your code this way:</p> <pre><code>int main () { fstream F ( soubor1, ios::out | ios::binary ); unsigned int x = 0xc4; F.write ( ( char * ) &amp;x, sizeof(unsigned int) ); x = 0x8d; F.write ( ( char * ) &amp;x, sizeof(unsigned int) ); F.close(); F.open ( soubor1, ios::in | ios::binary ); unsigned a[2]; F.read((char*)a, 2 * sizeof(unsigned int)); for (size_t i = 0; i &lt; 2; ++ i) cout &lt;&lt; a[i] &lt;&lt; " "; return 0; } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload