Files are in bytes. Integers are made of either 4 (32-bit) or 8 (64-bit) bytes. They can also be in little-endian (Intel) or big-endian (PowerPC) byte order.
In memory and in the disk file you wrote, num[0]
is char[4] {1, 0, 0, 0}
What you did is perfectly fine if you wanted to write the binary representation of your in-memory data.
In your character at a time print loop, if you wanted to see the number value of each byte you will need to cast it to int before cout
will format it correctly. The char
type is printed as an ASCII character. The only values you would see of that are from 33 to 127 and it would be the numbers, symbols and letters.
Try this for output:
while (fin.get(ch)){ std::cout << (int)ch << " ";}
Actually I would make a couple of other changes too and my version is like this:
#include <fstream>#include <iostream>int main() { int num[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0}; { std::ofstream fout("val.txt", std::ios::binary); fout.write((char *)num, sizeof num); } { std::ifstream fin("val.txt", std::ios::binary); char ch; while (fin.get(ch)) { std::cout << (int)ch << " "; } std::cout << std::endl; } return 0;}