-1

I am attempting to read a binary file byte by byte, for some simple encryption-decryption program:

iftream f("a.in", ios::binary | ios::in);
ofstream g("a.out");
char x1, x2;
int x,j=0;
f.seekg(0);
f.get(&x1,sizeof(char));
while(!f.eof())
{
    f.get(&x2,sizeof(char));
    if(j==10)
    {
        g<<'\n';
        j=0;
    }
    x=x1+x2;
    x1=x2;
    g<<x<<' ';
    j++;
}

The code compiles, but the while() is stuck in an infinite loop, which is because the get() functions are not actually reading anything from the file.

I imagine it may be because of the dereferencing of the chars, but get() would only accept a pointer as its first argument.

Could anyone point out where I went wrong, please?

Azareth
  • 5
  • 3
  • 3
    https://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong – Mat Jul 18 '17 at 07:54

2 Answers2

0

use f.read instead of get

 f.read(&x1, sizeof(char));
Ibrahim
  • 320
  • 1
  • 7
0
while(f.get(x2))
{
    if(j==10)
    {
        g<<'\n';
        j=0;
    }
    x=x1+x2;
    x1=x2;
    g<<x<<' ';
    j++;
}

@Mat provided explanation in this link.

Marek R
  • 27,988
  • 5
  • 42
  • 123
  • Thank you. It works for text files. Do you happen to have any idea on how to make it work for unicode? My idea was that, if I was to read byte by byte, I wouldn't have to worry about the multi-byte characters, but the program crashes if I run it with unicode text. – Azareth Jul 18 '17 at 15:46
  • create new question and link it, since this is another topic. – Marek R Jul 18 '17 at 23:07