Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
335 views
in Technique[技术] by (71.8m points)

c++ - Difference in using read/write when stream is opened with/without ios::binary mode

In my experiments with the following code snippet, I did not find any particular difference whether i created the streams with/without the ios:binary mode:

int main()
{
    ifstream ostr("Main.cpp", ios::in | ios::binary | ios::ate);
    if (ostr.is_open())
    {
        int size = ostr.tellg();
        char * memBlock = new char[size + 1];
        ostr.seekg(0, ios::beg);
        ostr.read(memBlock, size);
        memBlock[size] = '';
        ofstream file("trip.cpp", ios::out | ios::binary);
        file.write(memBlock, size);
        ostr.close();
    }
}

Here I am trying to copy the original source file into another file with a different name.

My question is what is the difference between the read/write calls(which are associated with binary file IO) when an fstream object is opened with/without ios::binary mode ? Is there any advantage of using the binary mode ? when to and when not to use it when doing file IO ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The only difference between binary and text mode is how the ' ' character is treated.

In binary mode there is no translation.

In text mode is translated on write into a the end of line sequence.
In text mode end of line sequence is translated on read into .

The end of line sequence is platform dependant.

Examples:

ASCII based systems:

LF    ('x0A'):      Multics, Mac OS X, BeOS, Amiga, RISC OS
CRLF  ('x0Dx0A'): Microsoft Windows, DEC TOPS-10, RT-11
CR:   ('x0D'):      TRS-80, Mac OS Pre X
RS:   ('x1E'):      QNX pre-POSIX implementation.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...