C++ binary files I/O, data lost when writing

  c++, char, ifstream, integer, ofstream

I am learning C++ with the "Programming: Principles and Practice Using C++" book from Bjarne Stroustrup. I am currently studying chapter 11 and I found an example on how to read and write binary files of integers (section 11.3.2). I played around with the example and used a .txt file (input.txt) with a sentence which I copied to another file (output.txt) and then copied back to the original file (input.txt).

#include "../std_lib_facilities.h"

void text_to_binary(ifstream &ifs, ofstream &ofs)
{
    for (int x; ifs.read(as_bytes(x), sizeof(char));)
    {
        ofs << x << 'n';
    }
    ofs.close();
    ifs.close();
}

void binary_to_text(ifstream &ifs, ofstream &ofs)
{
    for (int x; ifs >> x;)
    {
        ofs.write(as_bytes(x), sizeof(char));
    }
    ifs.close();
    ofs.close();
}

int main()
{
    string iname = "./chapter_11/input.txt";
    string oname = "./chapter_11/output.txt";

    ifstream ifs{iname, ios_base::binary};
    ofstream ofs{oname, ios_base::binary};

    text_to_binary(ifs, ofs);

    ifstream ifs2{oname, ios_base::binary};
    ofstream ofs2{iname, ios_base::binary};

    binary_to_text(ifs2, ofs2);

    return 0;
}

I figured out that I have to use sizeof(char) rather than sizeof(int) in the .read and .write command. If I use the sizeof(int) some chars of the .txt file go missing when I write them back to text. Funnily enough chars only goes missing if

x%4 != 0 (x = nb of chars in .txt file)

Now to my question, why does this happen? Is it because int’s are saved as 4 bytes?

Bonus question: Out of interest, is there a simpler/more efficient way of doing this?

Source: Windows Questions C++

LEAVE A COMMENT