Reading Binary File

I'm trying to read binary file into an array of chars, but what I get into console is plenty of strange symbols.

Here's my code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <conio.h>
#include <fstream>
#include <iostream>
using namespace std;

void main()
{
	char memory[256];
	ifstream file("decryptor.bin", ios::binary);

	while(file.is_open())
		file>>memory;
	cout<<memory<<endl;
	
	_getch();
}


What I did wrong?
Line 12 will read characters the first word from the file. It will also put a null character to mark the end. This is unsafe because it will write outside the array if the first word is more than 255 characters. If you want to read exactly 256 bytes you can use the write function.
file.write(memory, 256);
But this will not but a null character at the end so you should not pass it directly to cout <<.
Last edited on
the problem is that i get "╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠
╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠
╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠" instead of
"00 4004 0110 1A0A 0210 0310 020D 030D 0305
10 0305 0305 0305 320F 120E 0211 E607 000B"
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <fstream>
#include <vector>
#include <iomanip>

int main()
{
    std::ifstream file( "decryptor.bin", std::ios::binary ) ;
    std::vector<unsigned char> memory ;

    char c ;
    while( file.get(c) ) memory.push_back(c) ;

    std::cout << std::hex << std::noshowbase ;
    for( unsigned char c : memory )
    {
        static int cnt = 0 ;
        constexpr int LINE_SZ = 25 ;
        std::cout << std::setw(2) << std::setfill('0') << int(c)
                   << ( ++cnt % LINE_SZ == 0 ? '\n' : ' ' ) ;
    }
    std::cout << '\n' ;
}
"00 4004 0110 1A0A 0210 0310 020D 030D 0305
10 0305 0305 0305 320F 120E 0211 E607 000B"

Is this the literal contents of the file? If so, it is not binary.
Binary refers to the access mode, not the type of data. Any file can be opened in binary mode.
Topic archived. No new replies allowed.