Binary I/O

Hi.
I am in the need of using binary I/O in C++ and as I've never done this before, did some searching to find information on the subject. After a while of searching, I still couldn't find material that fully describes the topic. Maybe there is a book/article/tutorial that covers the subject? (reading all kinds of data, int's, strings, arrays etc. )
From the little I found, I have a specific question regarding the reading of an int.

1
2
3
4
5
6
  std::ifstream file("binaryLevel.txt", std::ios::in | std::ios::binary);
    file.seekg(std::ios::beg);

    file.read(reinterpret_cast<char*>(&Width), sizeof(int));
    std::cout<<reinterpret_cast<char*>(&Width)<<"\n";
    std::cout<<Width<<"\n";


I'm opening the file, setting the get pointer to the beginning of the file, reading sizeof(int) bytes of the file, which is one integer. Why do the outputs differ? (first is 64, second - 168637494). Do i have to cast that variable every time i need to use it?
Assuming you have int Width, then after reading it from the file, you simply need std::cout << Width << "\n";

In your example, line 5 doesn't make much sense to me. It is trying to display the address of the variable Width but asking for that address to be interpreted as a pointer to a string of characters instead. However, if the data file really did contain a string of characters, then it should have been treated directly as such.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
    int x = 1234;
    char str[] = "Some text";
    
    std::ofstream binout ("bin.dat", std::ios::binary);
    binout.write((char *) &x, sizeof x);
    binout.write(str, sizeof str);
    binout.close();

    int Width;
    char buffer[20];
    
    std::ifstream file("bin.dat", std::ios::binary);
    
    file.read(reinterpret_cast<char*>(&Width), sizeof(int));;
    std::cout << Width<<"\n";

    file.read(buffer, 10);
    std::cout << buffer << std::endl;

Output:
1234
Some text
Topic archived. No new replies allowed.