0

So I'm writing a little assignment and it requires input out of a .bin file. So I also wrote a little algorithm that transfers .txt into .bin (only numbers as per the assignment). The problem is, the function is... acting up. For some reason adds an extra byte on 12th number. No idea why. Also, obviously, breaks reading the number.

The question is, why and how do I fix that?

The algorithm itself:

        ifstream txtIn;
        txtIn.open("input.txt");
        if (!txtIn.is_open()) {
            cout << "Ошибка чтения входного .txt файла!\n";
            return;
        }
        ofstream binOut;
        long buf;
        binOut.open("input.bin");
        binOut.clear();
        do {
            txtIn >> buf;
            binOut.write((char*)&buf, sizeof(long));
        } while (!txtIn.eof());
        txtIn.close();
        binOut.close();
        cout << "Конверсия завершена\n";

Input.txt:

6 6
1 2 3 4 5 6
7 8 9 10 11 12
13 14 15 16 17 18
19 20 21 22 23 24
25 26 27 28 29 30
31 32 33 34 35 36

Input.bin:

06 00 00 00 06 00 00 00 01 00 00 00 02 00 00 00
03 00 00 00 04 00 00 00 05 00 00 00 06 00 00 00
07 00 00 00 08 00 00 00 09 00 00 00>0D<0A 00 00
00 0B 00 00 00 0C 00 00 00 0D 00 00 00 0E 00 00
//and so on//

Also, any outdated and/or archaic solutions are a part of the assignment. Unfortunately.

Johnny Cache
  • 969
  • 5
  • 9
  • Give [Why is iostream::eof inside a loop condition considered wrong?](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong) a read. `txtIn >> buf;` allows for the read to fail unchecked, end of file for example, and `buf` is used good or bad. – user4581301 Nov 20 '18 at 20:09
  • 1
    You need to open the file in binary to prevent text character translations. `binOut.open("input.bin", ios::binary);` – user4581301 Nov 20 '18 at 20:11
  • I'm aware of that, that is exactly why I'm using do while, not while. But thanks for showing me a better way. Still, that wasn't the question. – Johnny Cache Nov 20 '18 at 20:14
  • Well I'll be damned. I never used those and it never did anything like this. Makes a lot of sense, though - those modes are there for a reason. Thanks. – Johnny Cache Nov 20 '18 at 20:16
  • 1
    The question is WTF is that 0D doing in my file, yes? If you open a file in the default text mode, when you write the file assumes text output. That means certain characters, most notably newline (0x0A) are altered according to the rules for ... Never mind. Sounds like you just got it. – user4581301 Nov 20 '18 at 20:17
  • By the way `do/while`'s not good enough. You have to prevent a failed read into `bin` from being used. That means testing for failure AFTER reading and BEFORE using what you read. `do/while` tests after reading, good, but it also tests after using a potentially invalid `bin`, bad. – user4581301 Nov 20 '18 at 20:20

0 Answers0